Search code examples
c#wpfxamldata-binding

WPF only Binding to auto-implemented Property


I have a label that binds to a property, the binding only works when the property in the view model is auto-implemented.

In XAML:

<Label Content="{Binding MyProperty}" />

In ViewModel:

public virtual string MyProperty { get; set; }
//This code above works fine, but when i use it as below,binding doesn't work

private string _myProperty;
public virtual string MyProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

Solution

  • You're probably using a compile-time code generation utility to handle INotifyPropertyChanged.PropertyChanged for you, such as Fody or DevExpress. Such tools would handle an auto-implemented property but you'd need to handle your fully-implemented properties by explicitly raising the event after you change property value.

    private string _myProperty;
    public virtual string MyProperty
    {
        get { return _myProperty; }
        set
        {
            _myProperty = value;
            OnPropertyChanged(nameof(MyProperty)); // or however your base view-model class method signature for raising the event
        }
    }