我有一个自定义UserControl
,其中我将DataContext
设置为绑定到某个对象。我也想要启用或禁用基于绑定到父对象的布尔值的控件。但是,这会失败,只要设置了数据上下文,系统就会尝试在新数据上下文中找到所有其他绑定,而不是旧数据上下文中的所有其他绑定。 (这似乎有点不可思议,我反正。)如何在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
)?
你说得对,我的问题不清楚/不完整。我编辑它:用户控件的'DataContext'是'Zoo'类的有效实例。现在问题有点清楚了:'AnimalUserControl'需要一个不同的'DataContext',但是'IsEnabled'仍然应该绑定到当前的。 – Yellow 2014-10-07 14:51:28