Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to simplify setup of dependency properties in WPF and Silverlight?

I have a basic WPF/Silverlight user control code which includes a label that I want to set the value of from code which uses the control. Is there a way to simplify the requirements for definition of the dependency property and related events? It seems very noisy for what appears to be a simple coding task (a property, a method, and related wiring).

    private static DependencyProperty CountProperty;

    public MyWpfUserControl()
    {
        InitializeComponent();
        PropertyChangedCallback countChangedCallback = CountChanged;
        var metaData = new PropertyMetadata(countChangedCallback);
        CountProperty = DependencyProperty.Register("Count", typeof (int), typeof (MyWpfUserControl), metaData);
    }

    public int ItemsCount
    {
        get { return (int) GetValue(CountProperty); }
        set { SetValue(CountProperty, value); }
    }

    private void CountChanged(DependencyObject property,
                              DependencyPropertyChangedEventArgs args)
    {
        // Set the value of another control to this property
        label1.Content = ItemsCount;
    }
like image 851
WTLNewbie Avatar asked Apr 20 '11 04:04

WTLNewbie


1 Answers

You are right for sure that dependency properties are ugly and clumsy to work with. In fact, in your code example above, there are even bugs! You need to call the doctor -- Dr. WPF!

Here are Dr. WPF's snippets for all the dependency property flavors you desire:

  • Updated Code Snippets for WPF and Silverlight

There are also videos on his site showing him using them. Honestly I don't use them myself but I've been meaning to try them out. I do use the built in snippets.

like image 141
Rick Sladkey Avatar answered Oct 01 '22 21:10

Rick Sladkey