WPF Custom Control

I have been working on a WPF side project at work and wanted to make a quick note about creating and consuming WPF user controls. My example was much more replete with details but i was more interested in making a note of the code that ties your XAML directly to the code.

So you create control in the normal VS type of way and this will give you a really basic XAML page (I have removed some of the distracting details). I have dropped a label on the screen as this will serve as the control that I will programmatically manipulate.

    Width="Auto" Height="Auto" mc:Ignorable="d">

    <Canvas x:Name="ParentCanvas" PreviewMouseMove="ButtonMove" OpacityMask="#FF000000">
        <Label>Column="0" Grid. x:Name="NameLabel"  >ENGINEER</Label>

and here is the associated partial class that documents our implementation code.

public partial class Dog
	public static readonly DependencyProperty DogsNameProperty = 
		DependencyProperty.Register("Dogs Name", typeof(string), typeof(Dog), 
		 new FrameworkPropertyMetadata(DogsNamePropertyChange));

	public string DogsName
			return (string)base.GetValue(DogsNameProperty);
			base.SetValue(DogsNameProperty, value);
	private static void DogsNamePropertyChange(DependencyObject source, 
		DependencyPropertyChangedEventArgs e)
		(source as Dog).NameLabel.Content = (source as Dog).DogsName;
  • Basically we register the property using the DependencyProperty.Register method
  • We make it publicly accessible via the DogsName property
  • We monitor changes DogsNamePropertyChange


Technorati Tags: ,

Comment Section

Comments are closed.