数据绑定问题:如何使Binding值同时起作用?

时间:2018-11-09 15:22:17

标签: c# wpf xaml mvvm

我正在开发MVVM WPF应用程序,并且我正在尝试使用CheckBox。我想要的是将值绑定到模型属性(已完成)。但是,当我在调试会话中单击它时,它实际上并没有将我的IsChecked属性从默认的true更改为false。请参见下面的代码:

型号

public class MyModel:INotifyPropertyChanged
{
        private bool _isChecked;
        public bool IsChecked
        {
            get { return _isChecked; }
            set
            {
                if (_isChecked == value)
                    return;
                _isChecked = value;
                OnPropertyChanged();
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
}

查看

<StackPanel Orientation="Horizontal" Height="51" Width="667" Canvas.Left="10" Canvas.Top="45">
                <CheckBox IsChecked="{Binding IsChecked}" Command="{Binding CheckBoxClickCommand}"  Content="We're in the matrix" VerticalAlignment="Center" Margin="10,10,200,10"/>
            </StackPanel>

ViewModel

public class MyViewModel
{
    private MyModel _myModel = new MyModel();
    public ObservableCollection<MyModel> UrlsList { get; } = new ObservableCollection<MyModel>();
    public ICommand CheckBoxClickCommand { get; private set; }
    public MyViewModel()
    {
      CheckBoxClickCommand = new RelayCommand(CheckBoxOnClick);
    }
    public void CheckBoxOnClick()
        {
            var newList = new List<MyModel>();
            if (_myModel.IsChecked)
            {
                foreach (var url in UrlsList)
                {
                    if (!url.ExistsInDb)
                        newList.Add(url);
                }
            }
        }
}

当我调试并转到CheckBoxClickCommand中的if语句时,显然可以通过模型来获取属性值,但是它不会从默认的false更改为true。非常感谢您的任何帮助,谢谢!!

1 个答案:

答案 0 :(得分:1)

绑定到模型的属性:

<CheckBox IsChecked="{Binding Model.IsChecked}" ...>

要使其正常工作,必须从视图模型的 public属性返回模型:

private MyModel _myModel = new MyModel();
public MyModel Model { get { return _myModel; }}