我正在寻找阻止切换 RadioButton
的可能性,但仍然捕获 Click
事件。不幸的是,使用 Enabled=false
或 IsHitTestVisible=false
属性会阻止 Click
事件。
我想要实现的是:
1. 用户单击RadioButton
。
2. 从 Click
事件中调用一些方法,并使用作为参数传递的处理程序,但事件的 RadioButton
尚未更改。
3.当处理程序被调用时,根据结果我想切换或不切换RadioButton
。
最佳答案
我为您创建了简单的示例。
不要忘记取自 NuGet
Prism
包。
我创建了三个RadioButton
并为他们设置Func<bool>
来自一些 ViewModel。之后PreviewMouseDown
事件触发时,我调用当前委托(delegate),即 Func<bool>
来自Tag
属性。
View 模型:
namespace PostponeRadioButtonChange.Model
{
using System;
using System.Collections.Generic;
using Microsoft.Practices.Prism.Mvvm;
public class MainWindow : BindableBase
{
private List<Func<bool>> rbHandlers;
private string comment;
public List<Func<bool>> RbHandlers
{
get { return this.rbHandlers; }
private set { this.SetProperty(ref this.rbHandlers, value); }
}
public string Comment
{
get { return this.comment; }
set { this.SetProperty(ref this.comment, value); }
}
public MainWindow()
{
this.RbHandlers = new List<Func<bool>>
{
() =>
{
this.Comment = "First RadioButton clicked";
return false; // Here must be your condition for checking
},
() =>
{
this.Comment = "Second RadioButton clicked";
return false;
},
() =>
{
this.Comment = "Third RadioButton clicked";
return true; // For example, third not checked after click
}
};
}
}
}
查看内容(设计师);
<StackPanel>
<TextBox Text="{Binding Path=Comment, Mode=OneWay}"/>
<RadioButton Content="First"
PreviewMouseDown="RadioButtonMouseDown"
Tag="{Binding Path=RbHandlers[0], Mode=OneTime}"/>
<RadioButton Content="Second"
PreviewMouseDown="RadioButtonMouseDown"
Tag="{Binding Path=RbHandlers[1], Mode=OneTime}"/>
<RadioButton Content="Third"
PreviewMouseDown="RadioButtonMouseDown"
Tag="{Binding Path=RbHandlers[2], Mode=OneTime}"/>
</StackPanel>
查看(代码隐藏):
namespace PostponeRadioButtonChange
{
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using VM = PostponeRadioButtonChange.Model;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new VM.MainWindow();
}
private void RadioButtonMouseDown(object sender, MouseButtonEventArgs e)
{
var rb = (sender as RadioButton);
if (rb == null)
throw new InvalidCastException("RadioButtonMouseDown only for RadioButton's");
e.Handled = (rb.Tag as Func<bool>)?.Invoke() ?? false;
}
}
}
这对于最终解决方案来说并不好,但作为一个例子应该对您有帮助。您还可以创建 Command
在虚拟机中而不是事件处理程序中。
希望对你有帮助)
关于c# - 推迟 RadioButton 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993728/