wpf - 绑定(bind)到 datacontext parent-WPF 的属性

标签 wpf binding datagrid

我有一个数据网格:

 <DataGrid x:Name="DG" ItemsSource="{Binding}" AutoGenerateColumns="False">
     <DataGrid.Columns>
          <DataGridTextColumn Header="?" Binding="{Binding l}">
          </DataGridTextColumn>
     </DataGrid.Columns>
  </DataGrid>

在 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");
        }
    }

我希望 lName 将成为 DataGrid 中特定列的标题

我尝试这种方式:
 <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>

它不起作用

怎么能做到这一点?

最佳答案

试试 {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.LName}我也不会玩名字案例。 WPF 非常区分大小写。避免使用单一符号名称

关于wpf - 绑定(bind)到 datacontext parent-WPF 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707396/

相关文章:

WPF Datagrid - 设置每行的列可见性

c# - DataGrid只选择一行中的单元格

c# - WPF 在 TextBlock 中插入变量

WPF:TreeView 中的自定义 +-

javascript - 使用 ngChecked 将评级值绑定(bind)到 Angular 中的单选按钮

c# - 如何将列表的列表绑定(bind)到 ListView 控件

wpf - MVVM。在某些情况下向 View 添加代码是否合理?

c# - 将集合绑定(bind)到 ContextMenu 子菜单

c# - 在 WPF 中对分类数据进行分组

c# - 两个数据网格具有相同的来源,但输出的结果略有不同