c# - How to update binding to DataContext from within view model? -
this question has answer here:
i have binding:
<textblock text="{binding converter={local:converter}}" />
with converter:
public object convert(object value, type targettype, object parameter, cultureinfo culture) { var vm = (viewmodel)value; return vm.someproperty; }
changing someproperty
doesn't update value on screen. converter not called.
how update such binding within view model?
note: in real project converter used perform calculation , returning result. in fact multibinding
similar bindings different view models. had problem , able narrow down case simple binding
, binding not used bind property, this.
mcve xaml:
<stackpanel> <textblock text="{binding converter={local:converter}}" /> <button content="..." click="button_click" /> </stackpanel>
and code:
public partial class mainwindow : window { viewmodel _vm = new viewmodel(); public mainwindow() { initializecomponent(); datacontext = _vm; } void button_click(object sender, routedeventargs e) => _vm.someproperty += "b"; } public class viewmodel : inotifypropertychanged { public event propertychangedeventhandler propertychanged; public void onpropertychanged(string property) => propertychanged?.invoke(this, new propertychangedeventargs(property)); string _someproperty = "a"; public string someproperty { { return _someproperty; } set { _someproperty = value; onpropertychanged(nameof(someproperty)); } } } public class converter : markupextension, ivalueconverter { public override object providevalue(iserviceprovider serviceprovider) => this; public object convert(object value, type targettype, object parameter, cultureinfo culture) { var vm = (viewmodel)value; return vm.someproperty; } public object convertback(object value, type targettype, object parameter, cultureinfo culture) { throw new notimplementedexception(); } }
if viewmodel
set datacontext
of view. can bind property using <textblock text="{binding someproperty}" />
from comments, if bind whole viewmodel, because converter more stuff, convert type, or thing. have @ this: answer
Comments
Post a Comment