开发者

Get reference to Xaml object in view model

I have a an object created in Xaml:

<Grid>
   <MyObject/>
</Grid>

I need someway to bind the object myObject back to a property in my view model. I dont know whether this is possible, everything ive seen so far binds properties together, but any help would be greatly a开发者_运维百科ppreciated.


I am assuming what you want is your ViewModel to hold the actual visual control MyObject in it and your Grid to display it via MVVM.

This is possible through ContentControl in WPF.

Assuming your ViewModel has a property MyObjectView which holds MyObject...

   <Grid>
       <ContentControl Content="{Binding MyObjectView}" />
   </Grid>

Having said that you must take caution that same MyObjectView is not bound to any other content control as that will result in an error

"Specified element is already the logical child of another element. Disconnect it first"

And if that requirement is possible then you must excercise ContentTemplate option.

Let me know if this helps.


It is possible. It kinda breaks mvvm though.

You can attach an InvokeCommandAction to this object, and bind the CommandParameter to it via ElementBinding. Then in the callback of the command which you defined in the viewmodel, you will have a reference to this object from the CommandParameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜