如何在ComboBox绑定的ItemsSource为空时显示“No Items”内容?
解决ComboBox空集合时显示提示内容的问题
首先明确:TargetNullValue仅在绑定的MyCollection本身为null时生效,而空集合(比如new ObservableCollection<T>())不属于null,所以你的设置不会起作用。
下面提供两种可行的实现方式:
方法一:自定义ControlTemplate实现提示文本
修改ComboBox的模板,添加一个仅在集合为空时显示的提示元素:
<ComboBox ItemsSource="{Binding MyCollection, UpdateSourceTrigger=PropertyChanged}"> <ComboBox.Template> <ControlTemplate TargetType="ComboBox"> <Grid> <!-- 保留ComboBox原有基础模板元素 --> <ToggleButton x:Name="ToggleButton" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press" Style="{StaticResource ComboBoxToggleButtonStyle}"/> <ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding SelectionBoxItem}" Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> <Popup x:Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True"> <Border x:Name="DropDownBorder" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"> <ScrollViewer Margin="4,6,4,6"> <ItemsPresenter/> </ScrollViewer> </Border> </Popup> <!-- 空集合提示文本 --> <TextBlock Text="No Items" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="Gray" Visibility="Collapsed" x:Name="EmptyHint"/> </Grid> <ControlTemplate.Triggers> <!-- 集合为空时显示提示 --> <Trigger Property="HasItems" Value="False"> <Setter TargetName="EmptyHint" Property="Visibility" Value="Visible"/> </Trigger> <!-- 保留原有基础触发器 --> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </ComboBox.Template> </ComboBox>
注:如果项目中没有默认的ComboBoxToggleButtonStyle,可以直接使用系统默认模板,或替换为自定义的按钮样式。
方法二:用转换器将空集合转为含提示项的集合
创建转换器,当原集合为空时返回包含提示项的集合,否则返回原集合:
public class EmptyCollectionConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var enumerable = value as IEnumerable; if (enumerable == null || !enumerable.GetEnumerator().MoveNext()) { // 返回包含提示项的集合,需与原集合类型匹配,示例为字符串类型 return new ObservableCollection<string> { "No Items" }; } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
在XAML资源中声明转换器后,绑定时使用:
<Window.Resources> <local:EmptyCollectionConverter x:Key="EmptyCollectionConverter"/> </Window.Resources> <ComboBox ItemsSource="{Binding MyCollection, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource EmptyCollectionConverter}}"/>
这种方式无需修改模板,但提示项会被当作普通列表项,若要禁止选中,可额外设置IsEnabled="False"或在选择逻辑中过滤。
内容的提问来源于stack exchange,提问作者Snail
相关产品推荐
相关产品推荐

