[英]How can I get datacontext from hight level datacontext in wpf
我有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
的屬性。 在這種情況下,Grid 的數據上下文將是 B 類,INB 是其中定義的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.