我有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获得正确的值
发布于 2015-11-17 15:28:27
就像你自己弄清楚的那样,
<TextBlock Text="{Binding Path=DataContext.INB,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}"/>都会起作用的。它所做的就是沿着可视化树向上移动,直到找到类型为Grid的祖先,然后在该祖先中查找一个名为DataContext.INB的属性。在这种情况下,网格的数据上下文将是类B和其中定义的属性INB。
https://stackoverflow.com/questions/33748579
复制相似问题