[英]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.