c# - UserControl 中的依赖属性绑定(bind)

标签 c# wpf xaml data-binding mvvm

我的解决方案是在 MVVM 中实现的。 View 是一个承载用户控件的窗口。我为此 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);
    }
}

此属性绑定(bind)到我在 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>

此外,我已将代码隐藏中窗口的数据上下文初始化为 View 模型。问题是绑定(bind)似乎永远不会发生,并且永远不会为依赖属性调用 set 属性。我在这里错过了什么吗?

最佳答案

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

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

关于c# - UserControl 中的依赖属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9147219/

相关文章:

wpf - 删除文本框内填充?

wpf - 应使用哪个事件从 WPF 中的 TextBox(LostFocus、LostKeyboardFocus 等)更新模型?如何在WPF中设置事件的优先级?

WPF:如何让 ListViewItems 适合窗口宽度并使用 TextEllipsis

c# - 消息对话框中的文本输入?内容对话框?

c# - 如何使用 Path.GetInvalidPathChars 在较大的字符串中查找文件名?

c# - MemoryStream 和深度克隆

wpf - XAML 定义如何变成对象实例?

c# - 如何公开样式的内部控制?

c# - 在 Windows、MonoForAndroid 和 MonoTouch 上实现接口(interface)的差异

c# - .Net 究竟是什么?