2014-01-10 46 views
1

我有2個RadioButton控件以及2個ComboBox控件。Combobox DataTrigger

用戶可以選擇選項1或選項2.如果選擇選項1,我希望組合框被禁用,如果在組合框中有選定的值,我希望它被清除。反之亦然,如果選擇2。

<RadioButton Grid.Row="1" Grid.Column="0" Checked="rbOption1Checked" > 
    <TextBlock HorizontalAlignment="Right" Text="Option 1 (Optional):" VerticalAlignment="Top"/> 
</RadioButton> 
<ComboBox Grid.Row="1" Grid.Column="2" VerticalAlignment="Top" Name="cboOption1" SelectedItem="{Binding SelectedOption1, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding IsRegionSelected}"/> 

<RadioButton Grid.Row="2" Grid.Column="0" HorizontalAlignment="Left" Checked="rbOption2Checked"> 
    <TextBlock HorizontalAlignment="Right" Text="Option 2 (Optional):" VerticalAlignment="Top"/> 
</RadioButton> 
<ComboBox Grid.Row="2" Grid.Column="2" VerticalAlignment="Top" Name="cboOption2" SelectedItem="{Binding SelectedOption2, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding IsRegionSelected}" /> 

我想知道如何用DataTrigger來完成這項工作。我不知道從哪裏開始。我試過這樣的事情,但沒有什麼好開心的。

<RadioButton Grid.Row="2" Grid.Column="0" HorizontalAlignment="Left" Checked="rbOption2Checked"> 
    <TextBlock HorizontalAlignment="Right" Text="Option 2 (Optional):" VerticalAlignment="Top"/> 
</RadioButton> 
<ComboBox Grid.Row="2" Grid.Column="2" VerticalAlignment="Top" Name="cboOption2" SelectedItem="{Binding SelectedOption2, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding IsRegionSelected}"> 
    <ComboBox.Style> 
     <Style TargetType="ComboBox"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Path=IsChecked,ElementName=cboOption1}" Value="True"> 
        <Setter Property="ComboBox.IsEnabled" Value="False"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ComboBox.Style> 
</ComboBox> 

回答

4

這絕對可以通過觸發器完成。我認爲你遇到的第一個問題是常見問題,那就是你直接在你的控件上設置屬性,然後試圖在Style中覆蓋它;直接設置將會覆蓋樣式。這可能是爲什麼IsEnabled屬性永遠不會改變。

下面是一個RadioButtonComboBox,在組合時,纔會啓用,當相應的按鈕被選中

<RadioButton x:Name="radioButton1" Grid.Row="1" Grid.Column="0" > 
    <TextBlock HorizontalAlignment="Right" Text="Option 1 (Optional):" VerticalAlignment="Top"/> 
</RadioButton> 
<ComboBox Grid.Row="1" Grid.Column="2" VerticalAlignment="Top" Name="cboOption1" ItemsSource="{Binding ComboItems}"> 
    <ComboBox.Style> 
     <Style TargetType="ComboBox"> 
      <Setter Property="SelectedItem" Value="{Binding SelectedOption1, UpdateSourceTrigger=PropertyChanged}" /> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Path=IsChecked,ElementName=radioButton1}" Value="False"> 
        <Setter Property="IsEnabled" Value="False"/> 
        <Setter Property="SelectedItem" Value="{x:Null}" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ComboBox.Style> 
</ComboBox> 

什麼Style在這裏做的是設置默認其選擇的項目時,才設置了XAML綁定到DataContext。當radioButton1未被選中時,它將禁用控件並刪除綁定;這不會改變底層ViewModel中的任何內容。當按鈕被選中時,綁定將被再次設置,並且您的控件將反映最初選擇的任何值。