使用ObservableCollection绑定itemssource

时间:2012-07-13 11:45:23

标签: c# silverlight xaml mvvm

  

可能重复:
  WPF listbox empty datatemplate

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

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

3 个答案:

答案 0 :(得分: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}">

答案 1 :(得分: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>

答案 2 :(得分:0)

您也可以在C#视图模型中执行此逻辑。无需更改您的xaml代码。

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.