我有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
获得正确的值? 最佳答案
当您正确地弄清楚自己时,
<TextBlock Text="{Binding Path=DataContext.INB,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}"/>
将工作。
这是在可视化树中进行操作,直到找到
Grid
类型的祖先,然后在该祖先中查找名为DataContext.INB
的属性。在这种情况下,网格的数据上下文将是B类,而INB是其中定义的属性。关于c# - 我如何从WPF中的高级数据上下文中获取数据上下文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33748579/