我需要这一点,当单击UserControl时,TextBlock的可见性取决于IsChecked的值而改变。
我想做我的复选框,但遇到了这样的问题。System.NullReferenceException:“对象引用没有指向对象的实例。”在OnPropertyChanged方法中。此控件的逻辑是,当您单击可见性时,TextBlock应该变为隐藏或可见(取决于IsChecked值)。如果我不写OnPropertyChanged (“IsChecked”),那么当单击没有崩溃时,什么也不会发生。
UserCheckBox.xaml.cs
public partial class UserCheckBox : UserControl
{
public UserCheckBox()
{
InitializeComponent();
DataContext = this;
MouseUp += delegate (object sender, MouseButtonEventArgs e)
{
this.IsChecked = true;
};
}
private bool _IsChecked = false;
public bool IsChecked
{
get { return _IsChecked; } private set { _IsChecked = value; OnPropertyChanged("IsChecked"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}UserCheckBox.xaml
<UserControl x:Class="COP.UserCheckBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:COP"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="30" Background="#707070" Name="mainCheckBox">
<UserControl.Resources>
<local:VisibilityConvert x:Key="Convert"></local:VisibilityConvert>
</UserControl.Resources>
<Border BorderThickness="2" BorderBrush="Black">
<Grid>
<TextBlock FontFamily="Segoe UI Symbol" Text="" Visibility="{Binding ElementName=mainCheckBox, Path=IsChecked, Converter={StaticResource Convert}}"></TextBlock>
</Grid>
</Border>
VisibilityConvert.cs
class VisibilityConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value == true ? Visibility.Visible : Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}发布于 2018-09-27 19:52:41
您的UserControl必须使用INotifyPropertyChanged接口,否则WPF不知道要听这个类。
这样做:
public partial class UserCheckBox : UserControl, INotifyPropertyChanged另外,当IsChecked设置器应该是公共的时,它是私有的,否则就不能设置属性。
另外要注意的是,您不能在这个属性上使用Binding,因为它不是一个依赖项属性,所以只能在XAML中设置它,就像IsChecked="True"一样。您可能希望创建一个依赖项属性,请阅读这篇文章。
编辑:
因为我在测试您的代码OP时使用了IsChecked="True“,所以我忘记了您还需要订阅鼠标左键单击事件,在UserControl XAML上这样做:
MouseLeftButtonDown="OnMouseLeftButtonDown" Background="Transparent"然后在UserControl.xaml.cs中创建方法:
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IsChecked = !IsChecked;
}透明背景的原因是为了启用UserControl整个区域上的单击事件。
所有这些话,我强烈建议你扔掉这整件事。学习如何设置现有复选框控件的样式要好得多,而不是创建自己的复选框控件。
https://stackoverflow.com/questions/52543472
复制相似问题