UserControl中的依赖项属性绑定

本文关键字:属性 绑定 依赖 UserControl | 更新日期: 2023-09-27 18:22:38

我的解决方案是在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);
    }
}

此属性绑定到xaml:中的视图模型属性(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>

此外,我已经将codeehind中窗口的数据上下文初始化为视图模型。问题是绑定似乎从未发生过,并且从未为依赖属性调用set属性。我是不是遗漏了什么?

UserControl中的依赖项属性绑定

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

<UserControl Name="control" ...>
    <ItemsControl ItemsSource="{Binding ItemsList, ElementName=control}" />
</UserControl>