简体   繁体   中英

How do I bind a control to visualbrush in MVVM?

I have a visualbrush, where I want to set the visual to an element. A current example of my visual brush:

<VisualBrush Viewport="0,0,0.5,0.5" Visual="{Binding ElementName=Panel}"></VisualBrush>

However, I want to change the value in Visual, so that at different times, it can be showing the visual of different controls. My first idea was having:

Visual="{Binding ElementName={Binding VisElName}}"

But first off thats not allowed, and secondly my viewmodel would need to know the name of my elements. Is there a way to do this in MVVM, so that I can change the visual to another element at will?

That kind of depends on what's the actual logic that drives the change in the visual. For example, if it's some kind of business logic related state, you can expose a State property in your view model and use a converter to bind to it.

If it doesn't depend on a BL state, it would be OK MVVM-wise to modify the visual from the view's code behind, since it's considered to be purely view logic:

XAML

<VisualBrush x:Name="myBrush" Viewport="0,0,0.5,0.5" />

Code behind

myBrush.Visual = myPanel;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM