如何在WPF(MVVM)中绑定数据网格列的宽度 [英] How to bind datagrid columns width in WPF (MVVM)
问题描述
我正在尝试绑定数据网格列的宽度,但不起作用。
I am trying to bind a datagrid columns width but not working.
<DataGridTextColumn Binding="{Binding Name}" Width="{Binding GridNameWidth}" Header="Name" />
这是后端代码:
public int GridNameWidth
{
get
{
return 300;
}
}
从未触及后端代码。没有错误,但是 name
字段具有默认宽度。我想将宽度绑定到我的媒体资源。我不需要双向绑定,只需要在网格加载时绑定宽度即可。在wpf中可以吗?
The backend code is never touched. There are no errors but the name
field has a default width. I'd like to make width bind to my property. I don't need two-way binding just need the width to be binded when the grid loads. Is this possible in wpf?
推荐答案
DataGridTextColumn是一个抽象对象,它实际上不是VisualTree的一部分,因此它没有
The DataGridTextColumn is an abstract object that isn't actually part of the VisualTree, so it doesn't make use of an inherited DataContext like you would expect with other controls.
WPF知道如何解析诸如 Binding $ c之类的东西。 $ c>属性正确并将绑定转移到每个单元格,但是像Width这样的东西只是按原样求值,并且由于DataContext和VisualTree都没有按预期存在而无法正确求值。
WPF knows how to parse something like the Binding
property correctly and transfer the binding to each Cell, however something like Width simply gets evaluated as-is, and does not evaluate correctly because neither the DataContext nor VisualTree is there as expected.
一个常见的解决方案是改为使用静态数据源编写绑定。这是一个基于此答案的示例,该示例使用 x:Reference 引用XAML标记中的另一个控件:
A common solution is to write your binding using a static data source instead. Here's an example based on this answer, which uses x:Reference to refer to another control from the XAML markup :
{Binding Source={x:Reference MyDataGrid}, Path=DataContext.NameColumnWidth}
或者,您可以定义自己的 DataGridCellTemplate
控件,该控件的Width绑定到DataItem上的任何属性
Alternatively, you can define your own DataGridCellTemplate
with a control that has it's Width bound to whatever the property is on your DataItem
这篇关于如何在WPF(MVVM)中绑定数据网格列的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!