How to display default text “--Select Team --” in

2019-01-01 01:04发布

In a WPF app, in MVP app, I have a combo box,for which I display the data fetched from Database. Before the items added to the Combo box, I want to display the default text such as

" -- Select Team --"

so that on pageload it displays and on selecting it the text should be cleared and the items should be displayed.

Selecting data from DB is happening. I need to display the default text until the user selects an item from combo box.

Please guide me

标签: wpf combobox
23条回答
素衣白纱
2楼-- · 2019-01-01 01:31

No one said a pure xaml solution has to be complicated. Here's a simple one, with 1 data trigger on the text box. Margin and position as desired

<Grid>
    <ComboBox x:Name="mybox" ItemsSource="{Binding}"/>
    <TextBlock Text="Select Something" IsHitTestVisible="False">
           <TextBlock.Style>
                <Style TargetType="TextBlock">
                      <Setter Property="Visibility" Value="Hidden"/>
                      <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=mybox,Path=SelectedItem}" Value="{x:Null}">
                                  <Setter Property="Visibility" Value="Visible"/>
                             </DataTrigger>
                      </Style.Triggers>
                </Style>
           </TextBlock.Style>
     </TextBlock>
</Grid>
查看更多
其实,你不懂
3楼-- · 2019-01-01 01:32

I believe a watermark as mentioned in this post would work well in this case

There's a bit of code needed but you can reuse it for any combobox or textbox (and even passwordboxes) so I prefer this way

查看更多
怪性笑人.
4楼-- · 2019-01-01 01:35

Not tried it with combo boxes but this has worked for me with other controls...

ageektrapped blogpost

He uses the adorner layer here to display a watermark.

查看更多
几人难应
5楼-- · 2019-01-01 01:35

A little late but..

A more simple way would be to add a dummy data item to the list with parameter IsDummy=true and make sure it is not HitTestVisable and its hight is 1 pixel (using a Converter) so it wont be seen.

Than just register to SelectionChanged and in it, set the index to the dummy item index.

It works like a charm and this way you don't mess with the style and colors of the ComboBox or your application theme.

查看更多
不再属于我。
6楼-- · 2019-01-01 01:35
InitializeComponent()
yourcombobox.text=" -- Select Team --";

The above code demonstrates the simplest way to achieve it. After window load, declare the text of the combobox, using the .Text property of the combobox. This can be extended to the DatePicker, Textbox and other controls as well.

查看更多
登录 后发表回答