开发者

Checkbox twoway mode not updating viewmodel

Very simp开发者_开发百科le issue here. I have some checkboxes with their IsChecked bindings set to properties in my viewmodel.The binding mode is twoway. However, when they are checked, the viewmodel property isnt updated. I found a post about setting the clickmode of the checkbox and I have tried all the options:Hover, Press and Release. None of these fix the issue.


Is your property a nullable bool like the CheckBox.IsChecked?

Otherwise verify all that is needed for the MVVM pattern to work: your property is public with a getter and a setter, implementing INotifyPropertyChanged, etc.

Are the other properties binding properly? Your DataContext may be wrong...


Try this:

<Window x:Class="WpfTestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" >
    <StackPanel>
        <CheckBox Width="250" Height="30" IsChecked="{Binding Path=IsTrue, Mode=TwoWay}" />
        <TextBlock Text="{Binding Path=IsTrue}" />
    </StackPanel>
</Window>

Create ViewModel:

public class MainWindowViewModel :INotifyPropertyChanged
{
    private bool _isTrue;
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChange(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public bool IsTrue
    {
        get { return _isTrue; }
        set
        {
            _isTrue = value;
            OnPropertyChange("IsTrue");
        }
    }
}

Bind to View Model in MainWindow.cs code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜