Aabid Ali Aabid Ali - 4 years ago 90
C# Question

Dependency Property Binding in UserControl

My solution is implemented in MVVM. The view is a window which hosts a usercontrol. I have created a dependency property for this userControl as below :

public static DependencyProperty ListProperty = DependencyProperty.Register(
"ItemsList", typeof(List<RequiredClass>), typeof(UsercontrolTest));

public List<RequiredClass> ItemsList
get { return (List<RequiredClass>)GetValue(ListProperty); }
SetValue(ListProperty, value);

This property is bound to my viewmodel property (ListOfItems) in xaml :

<Window x:Class="TestProject.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Test:UserControlTest Grid.Row="0" ItemsList="{Binding Path=ListOfItems}" />
<Button Grid.Row="1" Content="AddItems" Click="Button_Click" />

Also I have initialized the datacontext of the window in codebehind to the viewmodel. Problem is the binding never seems to happen and the set property is never called for the dependency property. Am I missing something here?

Answer Source

Those getters and setters are never called by the binding system (hence you should never place additional code there). The property is probably being set but unless you do something with it in the declaration of the UserControl nothing will be displayed. e.g.

<UserControl Name="control" ...>
    <ItemsControl ItemsSource="{Binding ItemsList, ElementName=control}" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download