使用自己的(ItemSource.Count> 0)Silverlight MVVM绑定DataGrid可见性

时间:2014-12-08 05:56:13

标签: c# wpf silverlight mvvm datagrid

正如标题所示,当itemsource有0行时我想隐藏我的网格。

<sdk:DataGrid Name="RegionDataGrid" Visibility="{Binding <!-- WHAT_SHOULD_COME_HERE -->}" AutoGenerateColumns="False" VerticalAlignment="Top" IsReadOnly="False" Height="Auto" Width="Auto" >

1 个答案:

答案 0 :(得分:2)

首先你需要一个转换器,当List为空时它将返回Collapsed。

public class EmptyCollectionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ICollection list = (ICollection)value;

        if (list == null)
            return Visibility.Collapsed;

        return list.Count != 0 ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后你可以使用 RelativeSource 绑定值 Self 来绑定ItemsSource,

<sdk:DataGrid Visibility="{Binding ItemsSource, RelativeSource={RelativeSource Self}, Converter={StaticResource EmptyCollectionConverter}}" />