从内部的DataGridColumn绑定到DataContext属性绑定、属性、DataGridColumn、DataContext

2023-09-06 15:29:21 作者:守我所爱

属性在我的的DataContext

ViewModel {
    Visibility Foo;
}

但我无法弄清楚如何访问。在这种情况下,我认为它可能找以任何对象绑定到的DataGrid 的ItemsSource

But I cannot figure out how to access Foo inside a Column. In this case, I assume it's probably looking for Foo in whatever object is bound to the DataGrid ItemsSource

<DataGrid Visibility="{Binding Foo}">                      // works
    <DataGrid.Columns>
        <DataGridTextColumn Visibility="{Binding Foo}" />   // fails

我试图

I have tried

Binding="{Binding DataContext.Foo}"

和一堆东西的RelativeSource 标记。

此外,有一些方法来查看并选择属性从GUI绑定?

Also, is there some way to view and select a property to bind to from a GUI?

修改:原来,列本身并不FrameworkElements,所以他们无法找到DataGrid的祖先。然而可以使用该技术在下面的回答结合柱的CellTemplate的属性到DataContext

Edit: It turns out that the Columns themselves are not FrameworkElements, so they cannot locate the DataGrid ancestor. You can however use the technique in the answer below to bind properties of the CellTemplate of the Column to the DataContext.

推荐答案

这应该工作:

<DataGridTextColumn Visibility="{Binding Path=DataContext.Foo, RelativeSource={RelativeSource AncestorType=DataGrid}}" />

您说得对列被绑定到当前的项目 - 这就是为什么你需要使用的RelativeSource 得到的DataGrid,然后访问物业公司的DataContext

You're right about the column being bound to the current item - that's why you need to use RelativeSource to get the DataGrid, and then access the Foo property in its DataContext.

至于选择绑定到的财产,有WPF设计的属性面板和Visual Studio插件,如ReSharper的,它可以帮助,但最终他们没有在任何非简单的绑定,其他做这样一项伟大的工作,所以你再留下的是你自己和你的什么事情的理解。

As for selecting the property to bind to, there's the WPF designer's properties panel and visual studio addons such as Resharper which can help, but eventually they don't do such a great job at anything other than simple bindings, so what you're left with is yourself and your understanding of what's going on.