I have a user control that wraps a grid. I want to be able to set the underlying grid’s data source, but through the user control, like this:
<my:CustomGrid DataSource="{Binding Path=CollectionView}" />
I have set this up in the grid like this:
private static readonly DependencyProperty DataSourceProperty
= DependencyProperty.Register("DataSource", typeof(IEnumerable), typeof(CustomGrid));
public IEnumerable DataSource
{
get { return (IEnumerable)GetValue(DataSourceProperty); }
set
{
SetValue(DataSourceProperty, value);
underlyingGrid.DataSource = value;
}
}
But this doesn’t work (it doesn’t give me an error either). The data source is never set. What am I missing?
When WPF loads your control and encounters a DependencyProperty specified in XAML, it uses DependencyObject.SetValue to set the property value and not your class’s property. This makes custom code in property setters which are dependency properties pretty much useless.
What you should do is override the OnPropertyChanged method (from DependencyObject):
Alternately you can specify a callback when you register the DependencyProperty:
And do effectively the same as above in OnPropertyChanged in the callback: