[英]Show if ItemsControl.ItemsSource is null
问候,
我有一个ItemsControl,更改了哪个模板,以便为绑定的ItemsSource中的每个对象显示一个RadioButton。
但是ItemsSource可以为空,当它为空时,我想显示一个默认值。 诸如“绑定列表中没有可供您选择的项目”之类的内容...
我想到的一种方法是将ItemsControl.Visibility设置为Collapsed,并将TextBlock.Vsibility设置为Visible来显示文本。但这会包含更多数据。
如果ItemsControl.ItemsSource为null,是否可以显示默认值?
创建这个简单的转换器后:
public class AnyItemsToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var collection = value as IEnumerable;
if (collection == null)
return Visibility.Collapsed;
return collection.OfType<object>().Any() ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
您可以重写ItemsControl模板,以使用RelativeSource Binding支持此模板。
<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication1">
<UserControl.Resources>
<local:AnyItemsToVisibilityConverter x:Key="AnyItemsToVisibilityConverter" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<ItemsControl>
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Grid>
<TextBlock Text="No Items to Display"
Visibility="{Binding Items, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource AnyItemsToVisibilityConverter}}" />
<ItemsPresenter />
</Grid>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
</Grid>
</UserControl>
如果我理解正确,我认为您可以通过创建IValueConverter
来解决您的问题。
您不应该创建一个显示列表是否为空的Converter。 如果您的XAML,转换器和数据源是完全独立的项,则更好。 MVVM不是关于松散耦合的吗?
好吧,背后的代码是邪恶的。 感谢您指出了这一点。 我更正了源代码,现在它完全是声明式的样式:
<ControlTemplate x:Key="ListBoxTemplate" TargetType="ListBox">
<StackPanel>
<ItemsPresenter
Visibility="{Binding Path=NotEmpty,
Converter={StaticResource BoolToVisibilityConverter}}">
</ItemsPresenter>
<TextBlock Text="No items to select from"
Visibility="{Binding Path=Empty,
Converter={StaticResource BoolToVisibilityConverter}}"/>
</StackPanel>
</ControlTemplate>
<Style x:Key="ListBoxStyle2" TargetType="ListBox" >
<Setter Property="Template" Value="{StaticResource ListBoxTemplate}">
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
您可以做的一件事是,在检查ItemsControl.ItemsSource
为null之后,可以添加一个项目"The binded list contains no items for you to select"
。 我希望这能达到您的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.