... all I'm offering is the truth. Nothing more. RSS 2.0
# Friday, May 15, 2009

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 Grid.Column="0" Grid.Row="2" x:Name="NameLabel" HorizontalAlignment="Center" >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!

Technorati Tags: ,
Friday, May 15, 2009 3:39:24 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
WPF
Statistics
Total Posts: 316
This Year: 4
This Month: 0
This Week: 0
Comments: 29
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Mark Downie
Sign In
All Content © 2010, Mark Downie
DasBlog theme 'Business' created by Christoph De Baene (delarou)