开发者

How to effectively use inheritance in a DataBinding in WPF?

I have a very simple object model with a base class Person and two derived classes called Girl and Guy.

On my UI I have two ra开发者_如何学Cdiobuttons and I set the datacontext of my form to a property of type Person.

I would like to be able to bind my radiobuttons to "return" an instance of a Guy when the "Guy" radio button is checked and to "return" an instance of a Girl when the Girl is checked. Of course, I want the binding to be in TwoWay...

I don't manage to implement this kind of databinding, so any advice is welcomed.

Thanks for your help !


You could, potentially, use an IValueConverter to create the binding, and change the type of the fly.

However, I would recommend doing this in the ViewModel instead. The problem of trying to do this entirely in binding is that you'll end up creating new instances of the Guy/Girl as the user changes the radio box, which will cause you to lose values stored in the UI every time the user changes that option... By handling this in the ViewModel, you could easily cache these or not, at your discretion - basically giving you control over the generated object's lifetime.


Two way RadioButton binding is some tricky, here you have a solution for a common RadioButton binding problem.

wpf radio button binding - blog article

english version

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜