根据SelectedItem设置ComboBox的IsEnabled属性
我想根据另一个组合框中是否选择了某个项目来启用/禁用组合框。我可以通过在样式上设置触发器来使其工作,但这会覆盖我为组合框自定义的全局样式。有没有其他方法可以在不失去我的风格的情况下获得相同的功能?
<ComboBox Grid.Column="1" Grid.Row="1"
Name="AnalysisComboBox"
MinWidth="200"
VerticalAlignment="Center" HorizontalAlignment="Left"
ItemsSource="{Binding Path=AvailableAnalysis}">
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem,ElementName=ApplicationComboBox}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
I want to enable/disable a ComboBox based on if there is an item selected in another ComboBox. I was able to get it working by setting a trigger on the Style, but that overrides my custom global style for the combobox. Is there another way to get the same functionality without losing my style?
<ComboBox Grid.Column="1" Grid.Row="1"
Name="AnalysisComboBox"
MinWidth="200"
VerticalAlignment="Center" HorizontalAlignment="Left"
ItemsSource="{Binding Path=AvailableAnalysis}">
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem,ElementName=ApplicationComboBox}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要通过 Style 来执行此操作,您可以使用值转换器直接绑定 IsEnabled 属性,如下所示:
其中 NullToFalseConverter 是以下转换器实例的键:
You don't need to do this via a Style, you can bind the IsEnabled property directly using a value converter as follows:
Where NullToFalseConverter is a key to an instance of the followsing converter:
是的,您可以设置
BasedOn
属性来“继承”您的全局样式:您可以设置全局样式的键(而不是
{StaticResource {x:Type ComboBox}}
)(如果它不是隐式的)。但对于这个特定的任务,您不需要定义样式。您只需设置对 IsEnabled 属性的绑定,并使用转换器将另一个组合框的所选项目转换为布尔值:
Yes, you can set
BasedOn
attribute to "inherit" your global style:Instead of
{StaticResource {x:Type ComboBox}}
you can set the key of you global style (if it is not implicit).But for this particular task you don't need to define a style. You can just set a binding to IsEnabled property and use a converter to convert selected item of another combo box to a boolean:
您可以简单地拥有一个“正常”绑定,并使用一个值转换器来更改“值存在”==> true,“值为空”=>错误的。
You could simply have a "normal" binding, with a value converter for changing "value exists" => true, "value is null" => false.