【发布时间】:2014-03-24 14:46:15
【问题描述】:
在我的 WPF 应用程序中,我有一个绑定到视图模型中的集合的 DataGrid,但我希望第一列的宽度等于视图模型本身的属性,如下所示:
public ObservableCollection<Booking> Bookings
{
return repository.Bookings();
}
public int MaxWidth
{
return 100;
}
(我意识到像这样绑定到固定属性没有意义 - 这是为了演示目的)
<UserControl>
<DataGrid DataContext="{Binding Bookings}">
<DataGrid.Columns>
<DataGridTextColumn Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MaxWidth}" Header="Provider" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
</UserControl>
但如果我这样做,列的宽度将保持在默认值 - 即宽度足以容纳其值。
我做错了什么?
编辑:尝试了这个,看看发生了什么:
<Label Name="tricky" Content="500" Visibility="Collapsed"></Label>
...
<DataGridTextColumn Width="{Binding ElementName=tricky, Path=Content}" Header="Provider" Binding="{Binding Name}" />
什么都没做。不可以动态设置宽度吗?
【问题讨论】:
-
你的RelativeSource绑定不应该找到
DataGrid而不是UserControl吗? -
我不这么认为 - 我正在寻找的属性属于整个父 ViewModel,而不是 DataGrid。快速测试确认它没有任何区别。
-
@MattThrower 是正确的。您需要 UserControl 的 DataContext 范围,而不是 Booking 对象。 DataGrid 绑定何时发生?
-
嗯。这是基于 MVVM 的,所以我不控制绑定的时间。 Bookings 在 MaxWidth 之前填充,如果这就是您的意思的话。
-
我认为问题在于
DataGridTextColum不是可视树的一部分(可以使用Snoop 进行验证),因此绑定永远不会得到解决。从DataGridTextColumn获取的数据用于构建DataGridCell 模板,在构建模板时,未设置DataContext。我的建议是使用DataGridTemplateColumn,并指定您自己的具有所需宽度绑定的 CellTemplate。