2010-07-28 32 views
5

我正在尝试复制Word中的左/中/右对齐工具栏按钮。当您单击“左对齐”按钮时,取消选中“中心”和“右”按钮。我正在使用带有ToggleButtons的WPF ListBox。ToggleButton组:确保在列表框中始终选择一个项目

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

想法?强制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

是啊,我宁愿单选按钮也针对这种情况,但如果你想切换按钮,然后使用也许你可以IsEnabled属性绑定器isChecked所以它不能被cliked当它检查

+0

谢谢。在OnClick事件中:if(toggleButton.IsChecked == false)toggleButton.IsChecked = true; – 2010-08-01 23:25:45

+0

err其实我正在考虑更多关于这个 dnr3 2010-08-02 08:12:58

0

而不是实现这个ToggleButtons,我会使用RadioButtons与自定义模板。这可能会为你节省很多头痛。

+0

RadioButton还存在数据绑定的其他问题:http://geekswithblogs.net/claraoscura/archive/2008/10/17/125901.aspx。 ListBox让你绑定可能的选择而不是硬代码。 – 2010-08-01 23:25:09

+0

RadioButtons有其他问题:没有取消点击等等... – ANeves 2015-05-14 17:31:07

1

从切换按钮创建自定义控制在* .xaml.cs文件 ,在*的.xaml声明和定义控制

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(); 
     } 
    } 
} 

,我代替切换按钮: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}">   
相关问题