2014-10-07 57 views
0

我有一个自定义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> 

上述用户控制的DataContextZoo有效实例(我检查了这一点)。这给出了以下错误:

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)?

回答

0

您所做的是要求绑定在您的AnimalOnDisplay属性上搜索名为ZooIsClosed的属性。我们可以从你的代码中看到,这种关系不存在。

因为无论ZooIsClosedAnimalOnDisplay是你Zoo类的属性,所以你应该做的是设置你的DataContext你Zoo类实例(假设你的ZooControl有一个动物园实例的DependencyProperty),然后绑定到该实例,即性能IsZooClosedAnimalOnDisplay

下面是一些代码,让你开始,看它是否适合您的需要:通过使用RelativeSource跟踪到UserControl这样

<UserControl x:Class="MyProgramme.ZooUserControl" 
     xmlns:zoo="clr-namespace:Zoo.UserControls" 
     DataContext="{Binding Zoo.DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type zoo:ZooControl}}}"> 
    <StackPanel> 
     <Label Content="Welcome!" /> 
     <zoo:AnimalUserControl IsEnabled="{Binding ZooIsClosed}" /> 
    </StackPanel> 
</UserControl> 
+0

你说得对,我的问题不清楚/不完整。我编辑它:用户控件的'DataContext'是'Zoo'类的有效实例。现在问题有点清楚了:'AnimalUserControl'需要一个不同的'DataContext',但是'IsEnabled'仍然应该绑定到当前的。 – Yellow 2014-10-07 14:51:28

1

您可以设置BindingIsEnabled

<zoo:AnimalUserControl DataContext="{Binding AnimalOnDisplay}" 
     IsEnabled="{Binding DataContext.ZooIsClosed, 
        RelativeSource={RelativeSource AncestorType=UserControl}}"/> 

注意Path设置为DataContext.ZooIsClosed

此外,您的模型没有正确书写(我希望这只是示范)。

+1

是的,那可行,谢谢! (我知道,模型是示范性的,没有经过测试,并且无疑包含错误,对不起。) – Yellow 2014-10-07 14:52:56