2

可能重复:
WPF 列表框空数据模板

我的 Itemscontrol 的 Itemsource 绑定到 ObservableCollection。如果 ObservableCollection 中没有对象,如何编写代码以显示文本“列表为空”。

<ItemsControl Grid.Row="2" Name="itemsControl2" ItemsSource="{Binding RecentPatients}">
4

3 回答 3

1

你可能会使用TargetNullValue

请参阅:http: //msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.targetnullvalue

你可以像这样添加它

<ItemsControl Grid.Row="2" Name="itemsControl2" ItemsSource="{Binding RecentPatients, TargetNullValue=The list is empty}">
于 2012-07-13T11:53:25.027 回答
0

You can also do this logic in C# view model. No need to change your xaml code.

public sealed partial class MainPage : Page, INotifyPropertyChanged {
    private ObservableCollection<string> recentPatients = new ObservableCollection<string>();
    private IList<string> emptyList = new string[] { "This list is empty" };

    public MainPage()   {
        this.InitializeComponent();
        this.DataContext = this;
        this.recentPatients.CollectionChanged += OnCollectionChanged;
    }
    public IList<string> RecentPatients {
        get { return recentPatients.Any() ? recentPatients : emptyList; }
    }
    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)     {
        if (this.recentPatients.Count <= 1) {
            // It could be a change between empty to non-empty.
            this.OnPropertyChanged("RecentPatients");
        }
    }
    // implement the INotifyPropertyChanged pattern here.
于 2012-07-13T19:24:31.577 回答
0

我为此使用了一种风格

<Style x:Key="{x:Type ItemsControl}" TargetType="{x:Type ItemsControl}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
            <Setter Property="Background">
                <Setter.Value>
                    <VisualBrush Stretch="None">
                        <VisualBrush.Visual>
                            <TextBlock Text="The list is empty" 
                                       FontFamily="{StaticResource FontFamily}"
                                       FontSize="{StaticResource FontSize}"/>
                        </VisualBrush.Visual>
                    </VisualBrush>
                </Setter.Value>
            </Setter>
        </DataTrigger>
        <DataTrigger Binding="{Binding Items, RelativeSource={RelativeSource Self}}" Value="{x:Null}">
            <Setter Property="Background">
                <Setter.Value>
                    <VisualBrush Stretch="None">
                        <VisualBrush.Visual>
                            <TextBlock Text="The list is empty" 
                                       FontFamily="{StaticResource FontFamily}"
                                       FontSize="{StaticResource FontSize}"/>
                        </VisualBrush.Visual>
                    </VisualBrush>
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>
于 2012-07-13T12:53:27.787 回答