SYSK 340: Learning WPF — The Logical ‘Name’ Property


As you know, XAML allows you to give a name to declared elements.  For example:


    <TextBox Name=tb1></TextBox>


 


In essence, you’re setting the Name property of the TextBox class to ‘tb1’.  Why is it important?  Because if you’re using window.FindName method to find a named control amongst many controls on your form, then the WPF framework needs to get to the ‘Name’ property of that control.


 


But what if for whatever reason you can’t or don’t want to use ‘Name’ as the property to be used by FindName method?  For example, what if you want/need to use ID instead?  In essence, the ID property becomes the logical ‘name’…


 


To do that, you simply ‘map’ your ID property to the ‘Name’ concept by using the RuntimeNamePropertyAttribute.  For example, say you’ve created your own WPFCustomControls library with the following control (I’m only showing the shell of the control for brevity):


 


namespace WPFCustomControls


{


    [System.Windows.Markup.RuntimeNameProperty(“ID”)]


    public class MyTextBox : System.Windows.UIElement


    {


        private string _id;


 


        public string ID


        {


            get { return _id; }


            set { _id = value; }


        }


    }


}


 


 


With that, you can declare the namespace on the form that will be using that control:


xmlns:cc=clr-namespace:WPFCustomControls;assembly=WPFCustomControls


 


And now, you can declare the control itself:


<cc:MyTextBox ID=mytb1></cc:MyTextBox>


 


Finally, the real test – will this.FindName find MyTextBox instance with ‘mytb1’ passed in as the input parameter?  The answer is ‘yes’.  Give it a shot:


 


WPFCustomControls.MyTextBox tb = this.FindName(“mytb1”) as WPFCustomControls.MyTextBox;


if (tb != null)


    MessageBox.Show(tb.ID);


 


 


Important:  If you’re defining the control in same project, they you need to use x:Name (not ID) and the ID property will not be set.


 


 

Comments (0)

Skip to main content