UserControl中的依赖属性绑定

Aab*_*Ali 1 c# data-binding wpf xaml mvvm

我的解决方案是在MVVM中实现的.视图是一个托管用户控件的窗口.我已为此userControl创建了一个依赖项属性,如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此属性绑定到xaml中的viewmodel属性(ListOfItems):

  <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>
Run Code Online (Sandbox Code Playgroud)

此外,我已将codebehind窗口的datacontext初始化为viewmodel.问题是绑定似乎永远不会发生,并且永远不会为依赖项属性调用set属性.我在这里错过了什么吗?

H.B*_*.B. 9

那些getter和setter永远不会被绑定系统调用(因此你不应该在那里放置额外的代码).可能正在设置该属性,但除非您在UserControl声明中对其执行某些操作,否则将不会显示任何内容.例如

<UserControl Name="control" ...>
    <ItemsControl ItemsSource="{Binding ItemsList, ElementName=control}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)