错误版
- xaml
<Window
x:Class="checkboxtest.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:local="clr-namespace:checkboxtest"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Orientation="Vertical">
<CheckBox Name="checkbox" Content="java" IsChecked="{Binding ChkChecked}" />
<Button Click="Button_Click" Content="click" />
</StackPanel>
</Grid>
</Window>
- cs
using System.Windows;
namespace checkboxtest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public bool? ChkChecked { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
ChkChecked = !ChkChecked;
}
}
}
参考
正确版
using System.ComponentModel;
using System.Windows;
namespace checkboxtest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private bool? chkChecked = false;
public bool? ChkChecked
{
get
{
return chkChecked;
}
set
{
chkChecked = value;
RaisePropertyChanged("ChkChecked");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string _Prop)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(_Prop));
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ChkChecked = !ChkChecked;
}
}
}
注意点
同时有字段和属性
必须同时有字段和属性, 否则启动报错
空指针错误
有时候会报如下空指针错误
代码修改为如下即可
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string prop)
{
if (null != prop && IsLoaded)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
#endregion INotifyPropertyChanged