带有固定标题的组合框 [英] ComboBox with fixed Header

查看:36
本文介绍了带有固定标题的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 ComboBox 中显示默认文本,当用户选择 Combobox的项目时,也不得更改此文本,实际上是为此创建的:

I need to show a default text in my ComboBox, this text must not changed also when the user select an item of the Combobox, actually for do this I've created this structure:

<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>

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

this display as default text Select Countries but if I select an item the default text will disappear and the item selected will be displayed, how can I fix this?

推荐答案

您可以使用组合模板(参考帖子

You could use a Combined Template (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时才有效,我认为这对您而言不会有问题。其次,要在启动时显示文本,请绑定SelectedItem(例如,绑定到集合中的第一个项目)。

The way it works is described in the original answer. Note that the suggested solution will only work when IsEditable is set to false, I assume that won't be a problem in your case. Second, to get the text displayed at start up I bound SelectedItem (e.g. to the first item in the collection).

这篇关于带有固定标题的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆