c# - Inherited ViewModel passed to UserControl is treated as child ViewModel -


i have view mainwindow.xaml contains 2 buttons defined in button.xaml. button binds property isvisible defines whether button visible.

mainwindow.xaml:

<local:button datacontext="{binding buttonviewmodel1}" /> <local:button datacontext="{binding buttonviewmodel2}" /> 

button.xaml:

<stackpanel>     <button name="mybutton" visibility="{binding isvisible}">         <textblock>my button</textblock>     </button> </stackpanel> 

for button have 2 viewmodels: buttonviewmodel , buttonviewmodelchild.

buttonviewmodelchild inherits buttonviewmodel. both provide isvisible property:

buttonviewmodel:

public visibility isvisible {         {         return visibility.hidden;     } } 

buttonviewmodelchild:

public new visibility isvisible {         {         return visibility.visible;     } } 

the viewmodel of mainwindow.xaml contains property buttonviewmodel1 , buttonviewmodel2. these properties this:

public buttonviewmodel buttonviewmodel1 {         {         return new buttonviewmodelchild();     } }  public buttonviewmodelchildbuttonviewmodel2 {         {         return new buttonviewmodelchild();     } } 

the button should invisible if buttonviewmodel used datacontext button , visible if buttonviewmodelchild used.

i assumed button uses buttonviewmodel1 datacontext gets buttonviewmodel , other button buttonviewmodelchild. first button not visible , second would. both buttons visible though. wpf here? uses both times inherited view of instance. there way tell wpf use return type of property , not created-instance type?

i aware method hiding not best practice. change design curious why result not expected.

the property in binding path resolved reflection, hence finds subclass property, regardless of buttonviewmodel1 property type.

public buttonviewmodel buttonviewmodel1 {     { return new buttonviewmodelchild(); } // subclass instance } 

to avoid that, have return buttonviewmodel instance getter:

public buttonviewmodel buttonviewmodel1 {     { return new buttonviewmodel(); } } 

you declare property object, binding still work:

public object buttonviewmodel1 {     { return new buttonviewmodelchild(); } } 

besides that, should not let usercontrol operate specific view model (and make dependent of viel model class). instead should declare isbuttonvisible dependency property in usercontrol class, , bind bind this:

<stackpanel>     <button visibility="{binding isbuttonvisible,                          relativesource={relativesource ancestortype=usercontrol}}">         <textblock>my button</textblock>     </button> </stackpanel> 

usage be:

<local:button isbuttonvisible="{binding buttonviewmodel1.isvisible}" /> 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -