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