C# · 2月 12, 2022

c# – 基于SelectedItem设置ComboBox的IsEnabled属性

我想根据另一个Combo@R_801_2419@中是否选择了一个项来启用/禁用Combo@R_801_2419@.我能够通过在Style上设置触发器来使其工作,但这会覆盖我对组合框的自定义全局样式.有没有另一种方法来获得相同的功能而不会失去我的风格? <Combo@R_801_2419@ Grid.Column=”1″ Grid.Row=”1″ Name=”AnalysisCombo@R_801_2419@” MinWidth=”200″ VerticalAlignment=”Center” HorizontalAlignment=”Left” ItemsSource=”{Binding Path=AvailableAnalysis}”> <Combo@R_801_2419@.Style> <Style TargetType=”{x:Type Combo@R_801_2419@}”> <Setter Property=”IsEnabled” Value=”True” /> <Style.Triggers> <DataTrigger Binding=”{Binding SelectedItem,ElementName=ApplicationCombo@R_801_2419@}” Value=”{x:Null}”> <Setter Property=”IsEnabled” Value=”False” /> </DataTrigger> </Style.Triggers> </Style> </Combo@R_801_2419@.Style> </Combo@R_801_2419@>解决方法 您不需要通过Style执行此操作,您可以使用值转换器直接绑定IsEnabled属性,如下所示: <Combo@R_801_2419@ Grid.Column=”1″ Grid.Row=”1″ Name=”AnalysisCombo@R_801_2419@” MinWidth=”200″ VerticalAlignment=”Center” HorizontalAlignment=”Left” IsEnabled={Binding SelectedItem,ElementName=ApplicationCombo@R_801_2419@,Converter={StaticResource NullToFalseConverter}}” ItemsSource=”{Binding Path=AvailableAnalysis}”/>

其中NullToFalseConverter是以下转换器实例的键:

public class NullToFalseConverter: IValueConverter{ public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture) { return value == null; } public object ConvertBack(object value,System.Globalization.CultureInfo culture) { throw new NotImplementedException(); }}