如何根据属性隐藏wpf datagrid列

我有以下WPF示例程序:

XAML:

             

代码背后:

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Flowers rose = new Flowers(); rose.Leaves = new ObservableCollection(); rose.Flag = false; Leaf L1 = new Leaf(); L1.Color = "rot"; L1.Size = 3; rose.Leaves.Add(L1); Leaf L2 = new Leaf(); L2.Color = "gelb"; L2.Size = 2; rose.Leaves.Add(L2); this.DataContext = rose; } } 

模型类是:

 public class Leaf { public string Color { get; set; } public int Size { get; set; } } public class Flowers { public bool Flag { get; set; } public ObservableCollection Leaves { get; set; } } 

如您所见,如果Flag属性设置为false,我想隐藏第二个datagrid列。 但它不起作用。 我在Visual Studio输出窗口中收到以下绑定错误:

System.Windows.Data错误:4:无法找到绑定源,引用’RelativeSource FindAncestor,AncestorType =’System.Windows.Window’,AncestorLevel =’1”。 BindingExpression:路径= DataContext.Flag; 的DataItem = NULL; target元素是’DataGridTextColumn’(HashCode = 44856655); 目标属性是“可见性”(类型“可见性”)

我的代码中有关Visibility属性的错误是什么?

数据网格中的列是一个抽象对象,它不会出现在可视化树中,因此您不能使用RelativeSource绑定,因为它不会找到一个管理FrameworkContentElement,因此它不会起作用,因此您可以使用绑定。

一种方法是通过Sourcex:Reference ,为此您需要命名窗口并将列移动到其资源以避免周期性依赖性错误:

          

非常有趣。

DataGridTextColumn上的可见性不是DependencyProperty,也不能是数据绑定。 使用DataGridTemplateColumn并绑定模板中控件的可见性。

编辑:实际上,此声明仅适用于silverlight。 有关详细信息,请参阅此其他SO问题。

如何绑定DataGridColumn.Visibility?

我问过最容易判断一个属性是否依赖于此的方法。

我怎样才能最容易地确定属性是否是依赖属性?

我更喜欢使用Freezable的更优雅的方法。

     

HB提出的解决方案非常好,并且具有真正的WPF MVVM精神。 尽可能使用它。

在我的特殊情况下出了问题所以我以不同的方式出来,因为我的项目不是严格的MVVM,所以我可以使用编码解决方案。

在分配给列的CustomView.xaml名称中:

    ... 

在CustomView.xaml.cs中,我们有一个简单的属性,可以直接更改列的可见性:

 public Visibility MachinesColumnVisible { get { return MachinesColumn.Visibility; } set { if (value == MachinesColumn.Visibility) return; MachinesColumn.Visibility = value; } }