WPF ComboBox Text解决思路
WPF ComboBox Text
在WPF中,能不能设置ComboBox 默认的文本,但这个文本不属于ComboBoxItem,就是一个提示的效果!
我试了很多种方法。不好使啊。!
还有一种方法,就是把Text作为ComboBox的一项,默认选中,但默认时不调用Select_Changed事件。如何实现啊?
高手指点指点。!
------解决方案--------------------
方法1:SelectedIndex = -1 默认索引
方法2:
根据 ItemsSource 中 Item 的数据类型
定义一个新值,比如: null,并添加到 ItemsSource 源中
假定 ItemsSource 中的数据为 string 类型
然后添加 DataTemplate 并设置 DataTrigger
在WPF中,能不能设置ComboBox 默认的文本,但这个文本不属于ComboBoxItem,就是一个提示的效果!
我试了很多种方法。不好使啊。!
还有一种方法,就是把Text作为ComboBox的一项,默认选中,但默认时不调用Select_Changed事件。如何实现啊?
高手指点指点。!
------解决方案--------------------
方法1:SelectedIndex = -1 默认索引
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<Trigger Property="SelectedIndex" Value="-1">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<TextBlock Foreground="Gray" Text="- 请选择内容 -"/>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
方法2:
根据 ItemsSource 中 Item 的数据类型
定义一个新值,比如: null,并添加到 ItemsSource 源中
假定 ItemsSource 中的数据为 string 类型
var defaultItem = new string[] { null };
string[] oldItems = new string[] {"item1", "item2", "item3"};
var newItems = defaultItem.Union(oldItems);
this.comboBox1.ItemsSource = newItems;
然后添加 DataTemplate 并设置 DataTrigger
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=Name}"/>
<TextBlock x:Name="tblNull" Text="请选择内容" Visibility="Collapsed"/>