2010-07-28 35 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}">   
相關問題