绑定到数据上下文父级 WPF 的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14707396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding to property of datacontext parent- WPF
提问by Hodaya Shalom
I have a DataGrid:
我有一个数据网格:
<DataGrid x:Name="DG" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="?" Binding="{Binding l}">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
In DataContext of the DataGrid there is the collection of class X:
在 DataGrid 的 DataContext 中有 X 类的集合:
public ObservableCollection<xxx> col{ get; set; }// = DataContext of DG
private string lName;
public string LName
{
get { return lName; }
set
{
lName= value;
NotifyPropertyChanged("LName");
}
}
I want lName will be the header of a particular column in DataGrid
我希望 lName 将成为 DataGrid 中特定列的标题
I try this way:
我尝试这种方式:
<DataGridTextColumn Binding="{Binding l}">//l=prop of xxx class that contains the collection
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.LName,
RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
It did not work
这没用
how can do this?
怎么能做到这一点?
回答by Andrey Gordeev
Try {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.LName}
尝试 {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.LName}
Also I wouldn't play with name cases. WPF is pretty case-sensivity. Avoid of using one-symbol names
我也不会玩名称案例。WPF 非常区分大小写。避免使用单一符号名称
回答by Marius
Binding paths are also case-sensitive. There is no property lNamein your DC.
绑定路径也区分大小写。lName您的 DC 中没有任何财产。

