我有两个RadioButton控件和两个ComboBox控件。
用户可以选择选项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>发布于 2014-01-10 17:35:56
这绝对可以通过扳机来完成。我认为您所遇到的第一个问题,也是一个常见的问题,就是直接在您的控件上设置一个属性,然后尝试在Style中重写它;直接设置将覆盖样式。这可能就是为什么IsEnabled属性永远不会改变的原因。
下面是用于RadioButton和ComboBox的xaml,其中仅启用组合体,并且只有在选中相应的按钮时才设置其选择的项
<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在这里所做的是设置到DataContext的默认绑定。当不检查radioButton1时,它将禁用控件并删除绑定;这不会改变基础ViewModel中的任何内容。当选中该按钮时,将再次设置绑定,您的控件将反映最初选择的任何值。
https://stackoverflow.com/questions/21049521
复制相似问题