CheckBox绑定属性不会改变

时间:2018-02-03 05:48:41

标签: c# .net wpf

我有以下代码

Namespace WpfApplication1
{
    using System.ComponentModel;
    using System.Runtime.CompilerServices;

    using WpfApplication1.Annotations;
    using WpfApplication1.Enums;

    public class MainWindowViewModel : INotifyPropertyChanged
    {
        private bool _isItemEnabled;

        public MainWindowViewModel()
        {
            this.IsItemEnabled = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public bool IsItemEnabled
        {
            get
            {
                return this._isItemEnabled;
            }

            set
            {
                this._isItemEnabled = value;
                this.OnPropertyChanged(nameof(this.IsItemEnabled));
            }
        }


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



<CheckBox Grid.Row="0" Grid.Column="1" Margin="0,20" 
          IsChecked="{Binding Path = TimeIsEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged }"
          DataContext="{Binding ElementName = MainWindowViewModel}">
    TestIsEnabled
</CheckBox>

当我点击复选框时,位于文件后面的代码的属性TimeIsEnabled没有变化,断点也没有触发。我试图在视图模型中找到此属性,但结果是相同的。请帮助。

1 个答案:

答案 0 :(得分:2)

尝试将模式从OneWay更改为TwoWay(Mode=TwoWay)。如果您OneWay绑定该属性会更新用户界面,但用户界面不会更新该属性。

    <CheckBox Grid.Row="0" Grid.Column="1" Margin="0,20" 
              IsChecked="{Binding Path = TimeIsEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }"
              DataContext="{Binding ElementName = MainWindowViewModel}">
        TestIsEnabled
    </CheckBox>

在分析了您发送的其余代码后,我发现了一些错误。首先,您绑定了错误的属性TimeIsEnabled而不是IsItemEnabled。第二次尝试构建DataContext,就像我做的那样在下面的xaml文件中:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <CheckBox Grid.Row="0" Grid.Column="1" Margin="0,20" 
          IsChecked="{Binding IsItemEnabled,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }">
            TestIsEnabled
        </CheckBox>
    </Grid>
</Window>

你的MainWindowViewModel课很好。我试过这个例子,但它确实有用。