我需要在我的 ComboBox
中显示默认文本,当用户选择 Combobox
的项目时,此文本也不得更改。 ,实际上为此我创建了这个结构:
<ComboBox ItemsSource="{Binding AvailableNations}" Width="160" Height="55" Margin="0, 0, 0, 15"
Text="Select Countries" IsEditable="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Item.Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
此显示为默认文本
Select Countries
但是如果我选择一个项目,默认文本将消失,并且将显示所选项目,我该如何解决这个问题?
最佳答案
您可以使用组合模板 (ref post)
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="NormalItemTemplate" >
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Item.Name}" />
</DataTemplate>
<DataTemplate x:Key="SelectionBoxTemplate" >
<TextBlock>Select Countries</TextBlock>
</DataTemplate>
<DataTemplate x:Key="CombinedTemplate">
<ContentPresenter x:Name="Presenter"
Content="{Binding}"
ContentTemplate="{StaticResource NormalItemTemplate}" />
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}"
Value="{x:Null}">
<Setter TargetName="Presenter" Property="ContentTemplate"
Value="{StaticResource SelectionBoxTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ComboBox ItemsSource="{Binding AvailableNations}"
SelectedItem="{Binding SelectedNation}"
ItemTemplate="{StaticResource CombinedTemplate}"
Width="160" Height="55" Margin="0, 0, 0, 15" >
</ComboBox>
</Grid>
它的工作方式在原始答案中进行了描述。请注意,建议的解决方案仅在 IsEditable 设置为 false 时才有效,我认为在您的情况下这不会成为问题。其次,为了在启动时显示文本,我绑定(bind)了 SelectedItem(例如,绑定(bind)到集合中的第一个项目)。
关于c# - 具有固定标题的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39390123/