【发布时间】:2013-08-02 16:10:27
【问题描述】:
所以,我正在尝试使用一些 DependencyProperties 创建一个 UserControl,以便我可以重用代码。但是,有些属性没有更新,而另一些属性正在更新。更奇怪的是,即使对于那些正在更新的属性,“set”方法也根本没有被调用。
这是我的代码:
在 ViewModel 上:
public ICommand TestCommand = new DelegateCommand(x => MessageBox.Show("Ocorreu Evento"));
public List<string> TestList = new List<string> { "Hello","This","is","a","Test" };
在视图上:
<views:CustomizedList Header="Testing"
Items="{Binding TestList}"/>
用户控件视图:
<StackPanel>
<Label Content="{Binding Header}" />
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="Hello"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
用户控制代码:
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set
{
MessageBox.Show("New header is " + value);
SetValue(HeaderProperty, value);
}
}
public BindingList<object> Items
{
get { return (BindingList<object>)GetValue(ItemsProperty); }
set {
SetValue(ItemsProperty, value);
Console.WriteLine("Value was set with " + value.Count + " items.");
}
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(string),
typeof(ListaCustomizada));
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(BindingList<object>),
typeof(ListaCustomizada));
标题出现了,但项目没有出现。并不是说我添加了一些控制台打印来检查方法是否被调用,但没有任何显示,即使是标题。我将 UserControl 的 DataContext 设置为它自己。
有什么想法吗?
编辑:
根据@Garry Vass 的建议,我添加了一个回调函数。新代码是:
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(string),
typeof(ListaCustomizada), new PropertyMetadata("", ChangedCallback));
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(BindingList<object>),
typeof(ListaCustomizada), new PropertyMetadata(new BindingList<object>(), ChangedCallback));
private static void ChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine("Dependency property is now " + e.NewValue);
}
这样我可以看到 Header 的值发生变化,但没有发生 Items 的回调。
编辑:
将TestList改为属性而不是字段,类型为BindingList与用户控件中的数据一致,结果还是一样。
public BindingList<object> TestList { get; set; }
public ViewModel()
{
TestList = new BindingList<object> { "Hello", "This", "is", "a", "Test" };
}
编辑: 测试更多我发现错误来自这样一个事实,即用户控件上的DP绑定到视图上的DP,该DP绑定到VM。
编辑: 终于让它工作了。搜索得更深一点,我在 codeproject 找到了这个 link,它完美地解释了如何创建用户控件。
【问题讨论】:
-
WPF 中的
DependencyProperties是一种特殊的属性。话虽如此,您的Console.WriteLine()和MessageBox.Show()很可能是原因。DependencyProperties除了原来的 getter 和 setter 之外,不应该有任何额外的东西。 -
好吧,我在注意到没有任何变化后添加了它们,因此它们不是根本原因。我删除了它们并得到了相同的症状:标题值正在显示,但集合没有。从外观上看,它应该是双重绑定(ViewModel->View->UserControl)
标签: c# wpf data-binding user-controls dependency-properties