Wpf ToggleButton组:确保列表框中始终选择一个项目
我正在尝试复制Word中的左/中/右对齐工具栏按钮。单击“左对齐”按钮时,中间和右侧按钮将取消选中。我正在使用带有切换按钮的WPF列表框 问题是用户可以单击左对齐按钮两次。第二次单击会使按钮取消选中,并将基础值设置为null。我希望第二次单击什么也不做 想法?是否强制列表框始终有一个选定项?防止视图模型中出现空值(需要刷新ToggleButton绑定)Wpf ToggleButton组:确保列表框中始终选择一个项目,wpf,xaml,listbox,togglebutton,Wpf,Xaml,Listbox,Togglebutton,我正在尝试复制Word中的左/中/右对齐工具栏按钮。单击“左对齐”按钮时,中间和右侧按钮将取消选中。我正在使用带有切换按钮的WPF列表框 问题是用户可以单击左对齐按钮两次。第二次单击会使按钮取消选中,并将基础值设置为null。我希望第二次单击什么也不做 想法?是否强制列表框始终有一个选定项?防止视图模型中出现空值(需要刷新ToggleButton绑定) 我将使用带有自定义模板的单选按钮,而不是将其作为切换按钮来实现。这可能会帮你省去很多麻烦。是的,我也希望在这种情况下使用radiobutton
我将使用带有自定义模板的单选按钮,而不是将其作为切换按钮来实现。这可能会帮你省去很多麻烦。是的,我也希望在这种情况下使用radiobutton,但是如果你想使用togglebutton,那么也许你可以将isenabled属性绑定到ischecked,这样在选中它时就不能对其进行剪切。从togglebutton创建自定义控件,
在*.xaml.cs文件中,声明和定义控件
public class ToggleButton2 : ToggleButton
{
public bool IsNotCheckable
{
get { return (bool)GetValue(IsNotCheckableProperty); }
set { SetValue(IsNotCheckableProperty, value); }
}
// Using a DependencyProperty as the backing store for IsNotCheckable. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsNotCheckableProperty =
DependencyProperty.Register("IsNotCheckable", typeof(bool), typeof(ToggleButton2), new FrameworkPropertyMetadata((object)false));
protected override void OnToggle()
{
if(!IsNotCheckable)
{
base.OnToggle();
}
}
}
在*.xaml中,将ToggleButton替换为my:ToggleButton2,然后您可以将IsNotckable绑定到IsChecked,如下所示
<my:ToggleButton2 IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" IsNotCheckable="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked, Mode=OneWay}">
RadioButton在数据绑定方面存在其他问题:。列表框允许您绑定可能的选项,而不是硬代码。谢谢。在OnClick事件中:if(toggleButton.IsChecked==false)toggleButton.IsChecked=true;呃实际上我想的更多的是这样
<my:ToggleButton2 IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" IsNotCheckable="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked, Mode=OneWay}">