代码之家  ›  专栏  ›  技术社区  ›  Brian Low

ToggleButton组:确保列表框中始终选中一个项目

  •  5
  • Brian Low  · 技术社区  · 15 年前

    我正在尝试复制Word中的左/中/右对齐工具栏按钮。当您单击“左对齐”按钮时,中间和右按钮将取消选中。我正在使用带有切换按钮的WPF列表框。

    问题是用户可以单击左对齐按钮两次。第二次单击将取消选中按钮,并将基础值设置为null。我想第二次点击什么也不做。

        <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 回复  |  直到 5 年前
        1
  •  4
  •   dnr3    15 年前

    是的,对于这个例子我也更喜欢单选按钮,但是如果你想使用togglebutton,那么也许你可以将isenabled属性绑定到ischecked,这样当它被选中时就不能被剪辑

        2
  •  2
  •   user882729    14 年前

    从ToggleButton创建自定义控件,

        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,然后您可以将IsNotCheckable绑定到IsChecked,如下所示,

                  <my:ToggleButton2 IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}"  IsNotCheckable="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked, Mode=OneWay}">           
    
        3
  •  1
  •   FMM    15 年前

    我不会将其实现为ToggleButtons,而是将单选按钮与自定义模板结合使用。这可能会帮你省去很多头痛。

    推荐文章