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.
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MyNameSpage.Dog" x:Name="UserControl" Width="Auto" Height="Auto" mc:Ignorable="d"> <Canvas x:Name="ParentCanvas" PreviewMouseMove="ButtonMove" OpacityMask="#FF000000"> <Label>Column="0" Grid. x:Name="NameLabel" >ENGINEER</Label> </Canvas> </UserControl>
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 { get { return (string)base.GetValue(DogsNameProperty); } set { 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
Simple!
Comments are closed.