ToggleButton组:确保在ListBox中始终选择一个项目

6
我正在尝试在Word中复制左/居中/右对齐工具栏按钮。当您单击“左对齐”按钮时,居中和右侧按钮将取消选中状态。我正在使用带有ToggleButtons的WPF ListBox。
问题是用户可以单击左对齐按钮两次。第二次单击会取消选择该按钮并将基础值设置为null。我希望第二次单击不做任何操作。
有什么想法吗?强制ListBox始终具有一个选定项?防止视图模型中的null(需要刷新ToggleButton绑定)?
    <ListBox ItemsSource="{x:Static domain:FieldAlignment.All}" SelectedValue="{Binding Focused.FieldAlignment}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <ToggleButton IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}">
            <TextBlock Text="{Binding Description}" />
          </ToggleButton>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
3个回答

4

是的,对于这种情况我也更喜欢使用单选按钮,但如果您想要使用切换按钮,那么可以将isenabled属性绑定到ischecked上,这样在选中时就不能点击了。


感谢。在OnClick事件中:如果(toggleButton.IsChecked == false)toggleButton.IsChecked = true; - Brian Low
实际上,我更多地是这样考虑的:<ToggleButton IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" IsEnabled="{Binding Converter={StaticResource boolConverter}, RelativeSource={x:Static RelativeSource.Self}, Path=IsChecked}"> <TextBlock Text="{Binding Description}" /> </ToggleButton> - dnr3

2

从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 中,用 my:ToggleButton2 替换 ToggleButton,然后你可以像下面这样绑定 IsNotCheckable 到 IsChecked。请注意保留 HTML 标签。
              <my:ToggleButton2 IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}"  IsNotCheckable="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked, Mode=OneWay}">           

1

我建议不要使用 ToggleButtons 实现该功能,而是使用具有自定义模板的 RadioButtons。这样做可能会节省您很多麻烦。


RadioButton在数据绑定方面还有其他问题:http://geekswithblogs.net/claraoscura/archive/2008/10/17/125901.aspx。ListBox允许你绑定可能的选择,而不是硬编码。 - Brian Low

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接