c# - 带有固定标题的 ComboBox

标签 c# wpf xaml combobox

我需要在我的 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>

这显示为默认文本选择国家/地区,但如果我选择一个项目,默认文本将消失并显示所选项目,我该如何解决这个问题?

最佳答案

您可以使用组合模板 ( 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# - 带有固定标题的 ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39390123/

相关文章:

c# - 在导航之前取消等待方法的最佳方法?

c# - 以编程方式添加图像并将它们定位在 WPF Canvas 上

wpf - 如何证明包装面板中的项目?

c# - 使用 ClickOnce 使桌面图标模糊

wpf - WinForms - 像绘画一样的 WPF

c# - DataGrid 绑定(bind) - 不显示列表中的空条目

c# - WPF:控件失去其绑定(bind)

c# - 确定 Web 服务何时可用

c# - web.config文件的编译

c# - 为什么空赋值编译没有错误