UserControl中的依赖属性绑定

时间:2012-02-05 05:47:25

标签: c# wpf xaml data-binding 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);
    }
}

此属性绑定到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>

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

1 个答案:

答案 0 :(得分:9)

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

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