如何绑定只读 WPF 控件属性(例如 ActualWidth),以便在视图模型中可以访问其值? [英] How to bind a read-only WPF control property (eg ActualWidth) so its value is accessible in the view model?
问题描述
我想将控件的只读属性绑定到我的视图模型,以便该值在视图模型中可用.
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?
例如,我想将 ActualWidth
绑定到我的视图模型中的一个属性.宽度值是由 WPF 使用其布局逻辑生成的,因此我无法在我的视图模型中生成此值并将其推送到控件属性,这通常是这种情况.相反,我需要让 WPF 生成值并将其推送到视图模型.
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.
我只想使用 Mode=OneWayToSource
,但这不适用于只读属性:
I would just use Mode=OneWayToSource
, but this doesn't work for read-only properties:
<Border
...
ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
>
... child controls ...
</Border>
我目前的做法是处理边框的SizeChanged
,代码隐藏将值插入到视图模型中,但这感觉不太对.
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?
更新:我的问题实际上是这个问题的重复:将只读 GUI 属性推回 ViewModel
UPDATE: My question is effectively a duplicate of this one: Pushing read-only GUI properties back into ViewModel
推荐答案
描述了为什么这不起作用的实际问题 此处.
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.
我认为在 ViewModel 上调用一个方法是可以的.如果那是让您感到困扰的部分代码,也许您可以使用交互性来调用基于事件触发器 (SizeChanged) 的方法.
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).
这篇关于如何绑定只读 WPF 控件属性(例如 ActualWidth),以便在视图模型中可以访问其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!