在WPF中创建了一个简单的复选框。 单击可切换UI中的复选框状态。 我希望在双击复选框文本时更改复选框状态。请通过下面的代码帮助我。
xaml中唯一的控件:
<Grid>
<CheckBox Content="CheckBox" HorizontalAlignment="Left" Height="60" Margin="144,93,0,0" VerticalAlignment="Top" Width="392"/>
</Grid>
答案 0 :(得分:1)
我无法使用标准的CheckBox控件找到解决方案。我已经通过UserControl创建了自己的复选框。
DoubleClickCheckBox.xaml(UserControl)
<Grid VerticalAlignment="Center" HorizontalAlignment="Center" Loaded="Grid_Loaded">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<CheckBox Name="checkBox" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
<TextBlock Name="textBlock" MouseDown="TextBlock_MouseDown" TextAlignment="Center" Grid.Column="1" Margin="4,0,4,0"/>
</Grid>
DoubleClickCheckBox.xaml.cs(UserControl)
public partial class DoubleClickCheckBox : UserControl
{
public string Text { get; set; }
public bool IsChecked { get; set; }
public event EventHandler UserControlChecked;
public event EventHandler UserControlUnChecked;
public DoubleClickCheckBox()
{
InitializeComponent();
}
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
this.checkBox.IsChecked = this.IsChecked;
this.textBlock.Text = this.Text;
}
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
if(e.ClickCount == 2)
this.checkBox.IsChecked = !this.checkBox.IsChecked;
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
if (UserControlChecked != null)
UserControlChecked(this, EventArgs.Empty);
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
if (UserControlUnChecked != null)
UserControlUnChecked(this, EventArgs.Empty);
}
}
MainWindow.xaml
<Grid>
<local:DoubleClickCheckBox VerticalAlignment="Center" HorizontalAlignment="Center" Background="Aqua" Text="Test" IsChecked="False" UserControlChecked="DoubleClickCheckBox_UserControlChecked" UserControlUnChecked="DoubleClickCheckBox_UserControlUnChecked"/>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DoubleClickCheckBox_UserControlChecked(object sender, EventArgs e)
{
this.Title = "Checked";
}
private void DoubleClickCheckBox_UserControlUnChecked(object sender, EventArgs e)
{
this.Title = "UnChecked";
}
}
您可以使用此样式自定义所有内容。我仅定制了已检查和未检查的事件。将来取决于您。
编辑:正如帖子所有者所希望的,我再次启用了单击功能。 删除了CheckBox_PreviewMouseButtonDown事件。
答案 1 :(得分:-1)
如果只想在双击时切换复选框状态,则只需创建一个CheckBox_MouseDoubleClick事件并将IsChecked属性设置为true。但是请注意,该解决方案不在MVVM模式之内。