사용자 정의 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
에 바인딩하려고 : 같은 오류가 발생하고, 어느 동작하지 않는 ElementName
와
IsEnabled="{Binding ZooIsClosed, RelativeSource={RelativeSource Self}}"
합니다.
올바른 변수 (예 : ZooIsClosed
: Zoo
)에 어떻게 바인딩 할 수 있습니까?
당신 말이 맞아요, 제 질문은 불분명하고 불완전합니다. 나는 그것을 편집했다 : 사용자 정의 컨트롤의'DataContext'는'Zoo' 클래스의 유효한 인스턴스입니다. 이제 문제는 조금 더 명확 해졌습니다. AnimalUserControl은 다른 DataContext를 필요로하지만, IsEnabled는 현재의 것과 바인딩되어야합니다. – Yellow