Dependency Property Binding in UserControl

2019-04-02 14:53发布

问题:

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); }
    set
    {
        SetValue(ListProperty, value);
    }
}

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

  <Window x:Class="TestProject.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:Test="clr-namespace:TestProject"
          Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>             
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Test:UserControlTest Grid.Row="0" ItemsList="{Binding Path=ListOfItems}" /> 
        <Button Grid.Row="1" Content="AddItems" Click="Button_Click" />
    </Grid>
</Window>

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?

回答1:

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}" />
</UserControl>