繁体   English   中英

UserControl中的依赖项属性绑定

[英]Dependency Property Binding in UserControl

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

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中的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>

我也已经在viewmodel的代码后面初始化了窗口的datacontext。 问题在于绑定似乎从未发生过,并且从不为依赖属性调用set属性。 我在这里想念什么吗?

绑定系统永远不会调用这些getter和setter方法(因此,您永远不要在此处放置其他代码)。 该属性可能已设置,但是除非您在UserControl声明中对其进行任何操作,否则将不会显示任何内容。 例如

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM