2012-07-13 74 views

回答

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}"> 
+0

那麼它會工作與空列表,而不是空? – MBen 2012-07-13 11:54:05

+0

好點,檢查一下:http://stackoverflow.com/questions/699881/wpf-listbox-empty-datatemplate – 2012-07-13 11:57:11

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> 
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.