【发布时间】:2015-03-24 22:11:19
【问题描述】:
我有 2 个这样的课程:
public MyClass1: INotifyValueChanged
{
public Dictionary<int, Color> Property1
{
public event PropertyChangedEventHandler PropertyChanged;
get
{
return this.property1
}
set
{
PropertyChanged.ChangeAndNotify(ref this.property1, value, () => Property1);
}
}
}
public MyClass2: INotifyValueChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int Property2
{ get
{
return this.property2
}
set
{
PropertyChanged.ChangeAndNotify(ref this.property2, value, () => Property2);
}
}
}
ChangeAndNotify 是我使用的扩展方法,而不是普通语法来通知属性更改,因为这样我不需要将要更改的属性的名称键入为字符串,所以我认为它与问题无关。有需要我会发的。
我想将 MyClass2.Property2 绑定到 Rectangle.Fill。
为此,我必须创建一个 IMultiValueConverter,它将在 Property1 的字典中查找 Property2 并返回它的颜色。
在我的 XAML 中,我为转换器类创建了一个条目:
<local:MaterialConverter x:Key="MaterialsConverter" />
然后我尝试对 Rectangle 进行多重绑定:
<Rectangle>
<Rectangle.Fill>
<SolidColorBrush>
<SolidColorBrush.Color>
<MultiBinding Converter="{StaticResource MaterialsConverter}">
<Binding Path=Property1 />
<Binding Path=Property2 />
</MultiBinding>
</SolidColorBrush.Color>
</SolidColorBrush>
<Rectangle.Fill/>
</Rectangle>
在表单代码中,我有这 2 个类的 2 个变量:分别是 classObj1 和 classObj2。
在初始化和设置它们之后,我这样做是为了绑定:
rectangle.DataContext = class1Obj;
当然它不起作用,因为它是一个多重绑定,我在 DataContext 中只指定了 1 个元素,我收到一个错误,说 MyClass1 上不存在 Property2。
我不认为我可以将 2 个 DataContexts 设置为一个对象,但我可以以某种方式设置 XAML 中 2 个绑定之一的 Source 属性,因此一个绑定将来自矩形的 DataContext,另一个将从这个另一个地方来。但是我可以在哪里放置 class2Obj 或如何放置?
【问题讨论】:
-
在
MultiBinding中设置绑定时,您不能单独为每个绑定设置Source属性,而不是继承DataContext? -
ChangeAndNotify 是一种扩展方法,我使用它代替普通语法来通知属性已更改,因为这样我不需要将要更改的属性的名称键入为字符串 ...无论如何您都不需要...请参阅 MSDN 上的
CallerMemberNameAttribute页面。
标签: c# wpf multibinding