如何绑定只读 WPF 控件属性(例如 ActualWidth)以便在视图模型中可以访问其值?
我想将控件的只读属性绑定到我的视图模型,以便该值在视图模型中可用。
这样做的最佳方法是什么?
例如,我想将 ActualWidth 绑定到视图模型中的属性。宽度值是由 WPF 使用其布局逻辑生成的,因此我无法在视图模型中生成该值并将其推送到控件属性,就像通常的情况一样。相反,我需要让 WPF 生成值并将其推送到视图模型。
我只会使用 Mode=OneWayToSource
,但这不适用于只读属性:
<Border
...
ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
>
... child controls ...
</Border>
我当前执行此操作的方式是处理边框和边框的 SizeChanged
代码隐藏将值插入视图模型中,但这感觉不太正确。
有人已经解决这个问题了吗?
更新: 我的问题实际上是这个问题的重复: 将只读 GUI 属性推回 ViewModel
I want to bind a read-only property of a control to my view model so that the value is available in the view model.
What is the best way of doing this?
For example I'd like to bind ActualWidth
to a property in my view model. The width value is generated by WPF using its layout logic so I can't generate this value in my view model and push it to the control property, as would normally be the case. Instead I need to have WPF generate the value and push it to the view model.
I would just use Mode=OneWayToSource
, but this doesn't work for read-only properties:
<Border
...
ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
>
... child controls ...
</Border>
The way I am doing it currently is to handle SizeChanged
for the border and the code-behind plugs the value into the view model, but this doesn't feel quite right.
Has anyone already solved this problem?
UPDATE:
My question is effectively a duplicate of this one:
Pushing read-only GUI properties back into ViewModel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于为什么这不起作用的实际问题在此处进行了描述。
但是,创建抛出设置器以通过验证的给定解决方案在您的情况下不起作用。
我认为调用 ViewModel 上的方法就可以了。如果这是让您烦恼的代码隐藏部分,也许您可以使用交互性来调用基于事件触发器 (SizeChanged) 的方法。
The actual problem as to why this is not working is described here.
However, the given solution to create a throwing setter to pass the validation would not work in your case.
I think it's ok to call a method on the ViewModel. If that's the code behind part that bugs you, perhaps you can use interactivity to call a method based on an event trigger (SizeChanged).
你真的需要绑定吗?
do you really need a binding for that?