如何对 ColumnDefinition 的宽度或 RowDefinition 的高度进行数据绑定?
在 WPF 的视图-模型-视图模型模式下,我尝试对网格控件的各种定义的高度和宽度进行数据绑定,以便我可以存储用户在使用 GridSplitter 后设置的值。 然而,正常模式似乎不适用于这些特定属性。
注意:我将此作为参考问题发布,因为 Google 未能满足我的要求,我必须自己解决这个问题。 遵循我自己的答案。
Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.
Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建一个
IValueConverter
如下:然后您可以在绑定中使用该转换器:
Create a
IValueConverter
as follows:You can then utilize the converter in your Binding:
我发现了许多问题:
因此,我使用了以下代码:
和 XAML:
There were a number of gotchas I discovered:
Thusly, I used the following code:
And the XAML:
最简单的解决方案是简单地对这些属性使用字符串设置,以便 WPF 将使用 GridLengthConverter 自动支持它们,而无需任何额外的工作。
The easiest solution is to simply use string settings for these properties so that WPF will automatically support them using GridLengthConverter without any extra work.
由于您提出了
GridLength
和int
之间的转换,另一种可能性是创建一个IValueConverter
并在绑定到Width< 时使用它/代码>。
IValueConverter
还可以处理双向绑定,因为它们同时具有ConvertTo()
和ConvertBack()
方法。Another possibility, since you brought up converting between
GridLength
andint
, is to create anIValueConverter
and use it when binding toWidth
.IValueConverter
s also handle two-way binding because they have bothConvertTo()
andConvertBack()
methods.