我正在编写一个应用程序,其中我想禁用 ComboBox
中的一些项目,并且还想禁止/阻止选择已禁用的项目。请注意主窗口中的 ComboBox
有另一个 ComboBox 作为 ComboBox Item init(由 DataTemplateSelector
在运行时决定)。
使用下面的代码,我可以在 ComboBox 中禁用 ComboBox,但它不会阻止用户选择禁用的 ComboBox 项目。在禁止/阻止选择禁用项目方面的任何帮助都会有所帮助。
下面是代码片段
主窗口中的组合框:
<Grid>
<ComboBox HorizontalAlignment="Left" VerticalAlignment="Top"
Width="120" Margin="87.2,44.8,0,0"
ItemsSource="{Binding Cars}"
ItemsPanel="{DynamicResource ItemsPanelTemplateHorizontal}"
ItemTemplateSelector="{StaticResource QualityComboBoxTemplateSelector}"
SelectedItem="{Binding SelectedItm}"/>
</Grid>
数据模板选择器:
public class QualityComboBoxTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var element = container as FrameworkElement;
var dataTemplate = element.FindResource(((item is string) && item.Equals("Ferrari")) ?
"DataTemplateTopLevelCombobox2" : "DataTemplateTopLevelCombobox1") as DataTemplate;
return dataTemplate;
}
}
上述组合框的数据模板:
<DataTemplate x:Key="DataTemplateTopLevelCombobox1">
<Border BorderBrush="Black" BorderThickness="1" >
<TextBlock HorizontalAlignment="Left"
TextWrapping="Wrap" Text="{Binding}"
VerticalAlignment="Top"/>
</Border>
</DataTemplate>
<DataTemplate x:Key="DataTemplateTopLevelCombobox2">
<Border Width="100">
<ComboBox Text="Custom" Height="21.96"
ItemsSource="{Binding DataContext.Models, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
IsEnabled="{Binding DataContext.EnableCombo, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />
</Border>
</DataTemplate>
最佳答案
您可以通过将 ComboBoxItem
的 IsEnabled
属性设置为 false
来实现此目的;
因此 ComboBox 的 ItemSource
中的每个项目(即在您的情况下为 Cars
)都可以是具有某些属性(比如 IsSelectable
)的对象,指定是否它应该被启用或禁用,然后将它与样式一起使用以使项目不可选择。像这样的 -
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled" Value="{Binding IsSelectable}"/>
</Style>
更新:
<Grid>
<ComboBox
Width="120"
Margin="87.2,44.8,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
ItemTemplateSelector="{StaticResource QualityComboBoxTemplateSelector}"
ItemsPanel="{DynamicResource ItemsPanelTemplateHorizontal}"
ItemsSource="{Binding Cars}"
SelectedItem="{Binding SelectedItm}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter
Property="IsEnabled"
Value="{Binding IsSelectable}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</Grid>
关于c# - 禁止/阻止选择 wpf 中禁用的组合框项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889963/