Saturday 3 September 2011

Bubbling up control's property via dependency property

My today's study is a WPF user control that wraps a single combo box. The Text property of the latter I want to expose to consumers of the user control.

ReSharper 6.0 turns declaring a dependency property into an easy exercise.


public static readonly DependencyProperty SelectedCourierNameProperty =
    DependencyProperty.Register("SelectedCourierName", 
    typeof (string), typeof (CourierComboView), new PropertyMetadata(default(string)));


public string SelectedCourierName
{
    get { return (string)GetValue(SelectedCourierNameProperty); }
    set { SetValue(SelectedCourierNameProperty, value); }
}

Having the dependency property implemented,  I can proceed with creating an event handler for the SelectionChanged event of the combo box. I can do this either by modifying both the XAML and the code-behind, or just the code-behind (as below).


theCourierCombo.SelectionChanged += delegate { SelectedCourierName = theCourierCombo.Text; };

The other option, which I like much better, is invoking the SetBinding method of the user control (inherited from the FrameworkElement class).


SetBinding(SelectedCourierNameProperty,
    new Binding("Text") { Source = theCourierCombo, 
        Mode = BindingMode.OneWay });

And of course even better option would be using a view model.

No comments:

Post a Comment