gpt4 book ai didi

c# - 组合框数据触发器

转载 作者:行者123 更新时间:2023-12-02 01:07:25 24 4
gpt4 key购买 nike

我有 2 个 RadioButton 控件和 2 个 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>

最佳答案

这绝对可以通过触发器来完成。我认为您遇到的第一个问题,也是一个常见问题,是您直接在控件上设置一个属性,然后尝试在 Style 中覆盖它;直接设置将覆盖样式。这可能就是为什么 IsEnabled 属性永远不会改变的原因。

这是 RadioButtonComboBox 的 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 的默认绑定(bind)。当未选中 radioButton1 时,它会禁用控件并删除绑定(bind);这不会更改底层 ViewModel 中的任何内容。选中该按钮后,将再次设置绑定(bind),您的控件将反射(reflect)最初选择的任何值。

关于c# - 组合框数据触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21049521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com