当selectedItem为null时,在Combobox中显示“选择项目”

时间:2013-08-07 20:34:58

标签: c# wpf mvvm combobox

我有一个绑定到viewModel对象列表的WPF Combobox。最初,SelectedItem为null,因此Combobox显示为空白。

当所选项目为空时,我希望Combobox显示“选择项目”以引导用户从组合框中选择一些内容。有点像,一些文本框包含灰色文本,如“输入用户名”

关于如何做到这一点的任何想法?

编辑:

我最终使用了overlay a textbox, and change its visibility based on the value of SelecteItem

的建议

1 个答案:

答案 0 :(得分:-1)

试试这个 - 根据你的代码更改ItemsSource和SelectedValue。我刚刚展示了如何实现这一目标..

<ComboBox Height="23" Name="comboBox1" Width="120" ItemsSource="{Binding OCString,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=Window}}" SelectedValue="{Binding Selected,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}">
        <ComboBox.Style>
            <Style TargetType="{x:Type ComboBox}">
                <Style.Triggers>
                    <Trigger Property="SelectedIndex" Value="-1">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate>
                                    <ComboBox Text="Select an Item" IsReadOnly="True" IsEditable="True" ItemsSource="{Binding OCString,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=Window}}" SelectedValue="{Binding Selected,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}"/>

    </ControlTemplate>
    </Setter.Value>
    </Setter>
                    </Trigger>
                </Style.Triggers>
    </Style>
    </ComboBox.Style>
    </ComboBox>

或Simply-&gt;

<ComboBox Text="Select an Item" IsReadOnly="True" IsEditable="True" ItemsSource="{Binding OCString,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=Window}}" SelectedValue="{Binding Selected,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}"/>