如果你想使用单选按钮,你只需要进行一些小的调整以解决 RadioButton 的默认行为问题。
首先,你需要解决的问题是单选按钮的自动分组,根据它们共同的直接父容器进行分组。由于你不喜欢 "GroupName" 的 hack,你的另一个选择是将每个 RadioButton 放在其自己的网格或其他容器中。这将使每个按钮成为其自己组的成员,并强制它们基于它们的 IsChecked 绑定进行操作。
<StackPanel Orientation="Horizontal">
<Grid>
<RadioButton IsChecked="{Binding Path=CurrentMode, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Idle}">Idle</RadioButton>
</Grid>
<Grid>
<RadioButton IsChecked="{Binding Path=CurrentMode, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Active}">Active</RadioButton>
</Grid>
<Grid>
<RadioButton IsChecked="{Binding Path=CurrentMode, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Disabled}">Disabled</RadioButton>
</Grid>
<Grid>
<RadioButton IsChecked="{Binding Path=CurrentMode, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Running}">Running</RadioButton>
</Grid>
</StackPanel>
这使我想到了下一个解决方法,即确保在单击按钮后它不会停留在其选中状态,因为需要触发设置调用,因为您正在绑定IsChecked属性。 您将需要发送额外的NotifyPropertyChanged,但它必须被推送到Dispatch线程的队列中,以便按钮将接收通知并更新其视觉IsChecked绑定。 将此添加到您的ViewModel类中,它可能替换您现有的NotifyPropertyChanged实现,并且我假设您的类实现了在问题代码中缺少的INotifyPropertyChanged:
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
Dispatcher uiDispatcher = Application.Current != null ? Application.Current.Dispatcher : null;
if (uiDispatcher != null)
{
uiDispatcher.BeginInvoke(DispatcherPriority.DataBind,
(ThreadStart)delegate()
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
});
}
}
}
然后在您的CurrentMode的Setter中调用NotifyPropertyChanged(“CurrentMode”)。 您可能已经需要了这样的东西,因为您的Server的ModeChanged呼叫可能会在不是Dispatcher线程的线程上进行。
最后,如果您想要RadioButton有不同的Checked / Unchecked外观,则需要为它们应用样式。 快速搜索WPF RadioButton ControlTemplate最终找到了这个网站:http://madprops.org/blog/wpf-killed-the-radiobutton-star/。