如何绑定只读 WPF 控件属性(例如 ActualWidth)以便在视图模型中可以访问其值?

发布于 2024-10-07 20:30:40 字数 680 浏览 2 评论 0原文

我想将控件的只读属性绑定到我的视图模型,以便该值在视图模型中可用。

这样做的最佳方法是什么?

例如,我想将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遥远的她 2024-10-14 20:30:40

关于为什么这不起作用的实际问题在此处进行了描述。

但是,创建抛出设置器以通过验证的给定解决方案在您的情况下不起作用。

我认为调用 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).

走走停停 2024-10-14 20:30:40

你真的需要绑定吗?

    class MyVM
    {
        FrameworkElement _context;

        public MyVM(FrameworkElement context)
        {
            _context = context;
        }

        public double Width
        {
            get { return _context.ActualWidth; }
        }
    }

do you really need a binding for that?

    class MyVM
    {
        FrameworkElement _context;

        public MyVM(FrameworkElement context)
        {
            _context = context;
        }

        public double Width
        {
            get { return _context.ActualWidth; }
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文