英文:
Idiomatic way to bind to whether an ObservableCollection is empty?
问题
我想根据一个在其他地方使用的ObservableCollection
是否为空来使一个元素可见。传统上,如果您需要使可视更改反映视图模型的公开属性上的复杂条件,如果绑定到该属性并使用转换器,以便属性更改通知触发转换器的评估和视图更新。
但在这种情况下,这种方法不起作用:ObservableCollection
中的更改会触发CollectionChanged
而不是PropertyChanged
,正如它们应该 - 集合没有被替换。但非ItemsSource
属性的绑定期望PropertyChanged
事件作为触发事件。
当然,我可以想到一些基于监听CollectionChanged
的不太规范的方法,但是否有一种更干净的方法来实现这个目标?
英文:
I would like to make an element visible depending on whether an ObservableCollection
(used elsewhere) is empty. Traditionally, if you need visual changes to reflect an elaborate condition on an exposed property of the view model, if you bind to that property, and use a converter, so that property change notifications trigger the evaluation of the converter and the view updates.
But in this instance, this doesn't work: changes in the ObservableCollection
trigger CollectionChanged
, not PropertyChanged
, as they should - the collection wasn't replaced. But the binding for a non-ItemsSource
property expects PropertyChanged
events as trigger.
Of course I can think of a few dirty hacks based on listening to CollectionChanged
myself, but is there a clean way to do this ?
答案1
得分: 2
将可见性绑定到ObservableCollection的Count属性,并使用一个转换器,将整数转换为Visibility。当数字(或Count)为零时,可见性应为Hidden。
类似于这样:
[ValueConversion(typeof(int), typeof(Visibility))]
public sealed class HideWhenZeroConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value is not int number)
return null;
return number == 0 ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在XAML中使用:
<ListBox
ItemsSource="{Binding Path=Collection}"
Visibility="{Binding Path=Collection.Count, Converter={StaticResource HideWhenZero}}"
/>
请注意,代码和XAML部分已保持不变。
英文:
Bind the visibility to the count property of the ObservableCollection and use a converter, that converts an integer to Visibility. Visibility should be Hidden when number ( or Count ) is zero.
Something like this:
[ValueConversion(typeof(int), typeof(Visibility))]
public sealed class HideWhenZeroConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value is not int number)
return null;
return number == 0 ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
and in XAML:
<ListBox
ItemsSource="{Binding Path=Collection}"
Visibility="{Binding Path=Collection.Count,
Converter={StaticResource HideWhenZero}}"
/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论