6

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

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

想法?强制列表框总是有一个选定的项目?防止视图模型中的 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>
4

3 回答 3

4

是的,在这种情况下我也更喜欢单选按钮,但是如果你想使用切换按钮,那么也许你可以将 isenabled 属性绑定到 ischecked 以便在选中它时无法单击

于 2010-07-29T06:53:47.007 回答
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 中,将 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}">           
于 2011-08-07T12:46:51.633 回答
1

我不会将其作为 ToggleButtons 来实现,而是将 RadioButtons 与自定义模板一起使用。它可能会为您省去很多麻烦。

于 2010-07-28T19:38:39.763 回答