【发布时间】:2013-11-15 14:28:16
【问题描述】:
我有一个用户控件,它有一个组合框,绑定到它自己的依赖属性之一。
<UserControl x:Class="XamlParserComboBoxTest.ItemEditor" x:Name="aEditor">
<Grid>
<ComboBox Grid.Row="1"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=Colors}"
SelectedItem="{Binding ElementName=aEditor,
Path=Item.Color,
Mode=TwoWay}"/>
</Grid>
</UserControl>
此 DependencyProperty 填充有 Item 类型的实例:
public class Item : ViewModelBase
{
private Color _color { get; set; }
public Color Color
{
get { return _color; }
set
{
_color = value;
if (value == null)
{
Console.WriteLine("Color set to NULL");
}
Console.WriteLine(value);
OnPropertyChanged("Color");
}
}
}
public class Color
{
public string Name { get; set; }
}
当 UserControl 被另一个 UserControl 替换时,Item 的 Color 设置器将使用 NULL 值调用。绑定到其他控件的属性不会发生任何变化。
虽然我已经解决了这个问题,但我确实需要了解导致此问题的原因以及解决此问题的最佳方法。
编辑:根据堆栈跟踪,空值来自Item's 基类,但我不知道如何。完整的源代码可用here。要重现此问题,请启动它并按两次“显示项目”按钮。
【问题讨论】:
-
"When the UserControl is replaced with another UserControl"到底是什么意思?ItemsSource来自哪里? -
@HighCore,请查看源代码。通过将
ContentControl的内容绑定到由我的 ICommand 实现设置的属性,我只在窗口中心显示一个编辑器控件。