您可以使用该List
Count
属性来指示为空
例子:
public partial class MainWindow : Window
{
private ObservableCollection<string> myVar = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
MyList.Add("test");
}
public ObservableCollection<string> MyList
{
get { return myVar; }
set { myVar = value; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyList.Clear();
}
}
xml:
<Window x:Class="WpfApplication11.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication11"
Title="MainWindow" Height="136.3" Width="208" x:Name="UI">
<Grid DataContext="{Binding ElementName=UI}">
<Button Content="Clear" Click="Button_Click">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyList.Count}" Value="0">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
</Window>
如果您只使用IEnumerable<T>
它有点困难,因为IEnumerable
没有要绑定的公共属性,您将不得不制作一个转换器。
像这样的东西
public class IsEmptyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is IEnumerable)
{
var enumerable = (IEnumerable)value;
foreach (var item in enumerable)
{
return false;
}
}
return true;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
xml:
<Window x:Class="WpfApplication11.MainWindow"
xmlns:local="clr-namespace:Namespace for converter"
....
....
<Window.Resources>
<local:IsEmptyConverter x:Key="IsEmptyConverter" />
</Window.Resources>
....
....
<DataTrigger Binding="{Binding Path=MyList, Converter={StaticResource IsEmptyConverter}}" Value="true">