2014-01-10 40 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中的任何内容。当按钮被选中时,绑定将被再次设置,并且您的控件将反映最初选择的任何值。