XAML Binding to property

戏子无情 提交于 2019-12-05 04:11:33

You need to implement some form of change notification in order for your check box to be "aware" of any changes to the property. The best bet is to use one of the many MVVM frameworks out there, if not, implement INotifyPropertyChanged in your ViewModel.

Also, typically in WPF, we do not set the DataContext of individual controls but set the DataContext of the Window or User Control to a ViewModel...

Here is an example of a property with change notification through one of the MVVM frameworks:

private bool createTrigger;
public bool CreateTrigger
{
    get { return createTrigger; }
    set { createTrigger = value; NotifyPropertyChanged(m => m.CreateTrigger); }
}

As you can see a simple auto-implemented property cannot be used for data binding in WPF...

I'd recommend going through Data Binding Overview over on MSDN...

astronought
<CheckBox x:Name="chbRemember1"  IsChecked="{Binding Path=RememberUser, Mode=TwoWay}"/>

 

public class SessionData : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(info));
    }


    bool _rememberUser;
    public bool RememberUser
    {
        get
        {
            return _rememberUser;
        }
        set
        {
            _rememberUser = value;
            NotifyPropertyChanged("RememberUser");
        }
    }
}

You cannot bind to static properties as static properties cannot raise the PropertyChanged event. You will, of course, need INotifyPropertyChanged. But that is not relevant with static properties. You simply cannot bind to static properties. (You can in WPF and Silverlight)

Try like this, note that the property is not static but the backing field is:

public class SessionData : INotifyPropertyChanged
{
    private static bool _rememberUser;

    public event PropertyChangedEventHandler PropertyChanged;

    public bool RememberUser
    {
        get { return _rememberUser; }
        set
        {
            _rememberUser = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
this.DataContext = new SessionData();
<CheckBox x:Name="chbRemember1"  IsChecked="{Binding RememberUser, Mode=TwoWay}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!