How to bind a read-only WPF control property (eg ActualWidth) so its value is accessible in the view model? [duplicate]
Asked Answered
E

2

25

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

Epicarp answered 14/12, 2010 at 10:57 Comment(1)
Check these links social.msdn.microsoft.com/Forums/en-US/wpf/thread/… #1083724Leonardoleoncavallo
A
1

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).

Albata answered 14/12, 2010 at 11:14 Comment(0)
V
-1

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; }
        }
    }
Valenza answered 14/12, 2010 at 11:3 Comment(2)
Its an interesting idea, but the UI objects are generated from the view model objects, so I couldn't pass in the FrameworkElement via the constructor. I suppose I could bind the view model object to the FrameworkElement later but this sounds like it would violate a WPF principle (I might be violating it anyway but at least in my current implementation the view model doesn't explicitly access the UI).Epicarp
generally a ViewModel should not be aware (Read: Have references to) UI dependent code. In this case you would need references to WPF specific assemblies.Manchester

© 2022 - 2024 — McMap. All rights reserved.