我有A班和B班:
public class A : INotifyPropertyChanged
{
private string _ina;
public string InA
{
get
{
return _ina;
}
set
{
_ina = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("InA"));
}
}
}
public A()
{
InA = "INA";
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class B : INotifyPropertyChanged
{
private string _inb;
public string INB
{
get
{
return _inb;
}
set
{
_inb = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("INB"));
}
}
}
public B()
{
INB = "B_inb";
}
public event PropertyChangedEventHandler PropertyChanged;
}
和xaml(local是A和B类所在的命名空间别名):
<Grid>
<Grid.DataContext>
<local:B/>
</Grid.DataContext>
<StackPanel>
<StackPanel.DataContext>
<local:A/>
</StackPanel.DataContext>
<TextBlock Text="{Binding Path=InA}"/>
<TextBlock Text="{Binding Path=INB }"/>
</StackPanel>
</Grid>
我知道第一个TextBlock
将获得正确的值,但第二个不能。但是,我怎样才能让DataContext
让第二个TextBlock
从网格的DataContext
中获取正确的值,而不是从stackpanel的DataContext
中获取正确的值?
答案 0 :(得分:1)
正如你自己弄清楚的那样,
<TextBlock Text="{Binding Path=DataContext.INB,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}"/>
会奏效。
这样做是在可视树上,直到找到类型为Grid
的祖先,然后在该祖先中查找名为DataContext.INB
的属性。在这种情况下,Grid的数据上下文将是B类,INB是在其中定义的属性。