【发布时间】:2014-10-07 14:20:19
【问题描述】:
我有一个自定义的UserControl,我将DataContext 设置为某个对象的绑定。我还想根据绑定到父对象中的布尔值来启用或禁用控件。然而,这失败了,因为一旦设置了数据上下文,系统就会尝试在新数据上下文中查找所有其他绑定而不是旧数据上下文。 (无论如何,这对我来说似乎有点奇怪。)
public class Animal
{
public string Name;
}
public class Zoo
{
public Zoo ()
{
AnimalOnDisplay = new AnimalOnDisplay { Name = "Tyrannosaurus" };
}
public bool ZooIsClosed;
public Animal AnimalOnDisplay;
}
static void Main()
{
ZooUserControl control = new ZooUserControl ();
control.DataContext = new Zoo();
control.Show();
}
XAML:
<UserControl x:Class="MyProgramme.ZooUserControl"
xmlns:zoo="clr-namespace:Zoo.UserControls">
<StackPanel>
<Label Content="Welcome!" />
<zoo:AnimalUserControl DataContext="{Binding AnimalOnDisplay}"
IsEnabled="{Binding ZooIsClosed}" />
</StackPanel>
</UserControl>
上述用户控件的DataContext 是Zoo 的有效实例(我检查了这个)。这会产生以下错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'ZooIsClosed' property not found on 'object' ''Animal`1' (HashCode=44290843)'.
BindingExpression:Path=ZooIsClosed; DataItem='Animal`1' (HashCode=44290843); target element is 'AnimalUserControl' (Name='');
target property is 'IsEnabled' (type 'Boolean')
很明显,它在错误的地方寻找ZooIsClosed。我尝试将它绑定到当前的DataContext,如下所示:
IsEnabled="{Binding ZooIsClosed, RelativeSource={RelativeSource Self}}"
这会产生同样的错误,并带有 ElementName,这也不起作用。
如何将它绑定到正确的变量(即Zoo 中的ZooIsClosed)?
【问题讨论】:
标签: c# wpf binding datacontext