Michbeckable
Michbeckable

Reputation: 1891

Get XAML View element without breaking MVVM

I need a reference to a Visual (one element of a XAML View Window) in my ViewModel to work with VisualTreeHelper methods like VisualTreeHelper.GetDescendantBounds(Visual reference) but I do not want to break MVVM rules and just name the viewport3d and provide it as a reference when instancing my ViewModel.

Currently I am binding the geometry as content like this to my ViewModel:

<Viewport3D>
     <ModelVisual3D Content="{Binding SceneContent.Content}"/>
</Viewport3D>

But I do not see the MVVM possibility to get the containing ModelVisual3D into my ViewModel. Is there a standard (may be data-binding) approach to this in MVVM applications?

Upvotes: 0

Views: 1380

Answers (1)

Sheridan
Sheridan

Reputation: 69985

Using MVVM, we don't 'get view elements'. If you need to do something with a UI element, then that has nothing to do with MVVM. If you need to use the VisualTreeHelper.GetDescendantBounds method, then once again, that has absolutely nothing to do with MVVM... why do so many people claim to use MVVM, but know nothing about it?

Therefore, your question is invalid. It is entirely appropriate in situations like these for you to use the code behind. In fact, this is a perfect example of when we should use the code behind when following the MVVM methodology. If it is only UI related, then it has no purpose being in a view model, so simply don't put it there.

Please read the answer to the What are MVVM limitations? question to get some further insight into MVVM.

Upvotes: 3

Related Questions