WPF转换器和ObservableCollections [英] WPF Converters and ObservableCollections
问题描述
我将ObservableCollection绑定到一个控件,该控件具有一个转换器,可以根据集合是否具有任何值来更改其可见性:
I'm binding an ObservableCollection to a control which has a converter to change its visibility depending on if the collection has any values or not:
简化示例:
XAML:
<Window.Resources>
<local:MyConverter x:Key="converter"/>
</Window.Resources>
<Grid x:Name="grid">
<Rectangle Height="100" Width="200" Fill="CornflowerBlue"
Visibility="{Binding Converter={StaticResource converter}}"/>
<Button Content="click"
HorizontalAlignment="Left" VerticalAlignment="Top"
Click="Button_Click"/>
</Grid>
C#:
ObservableCollection<string> strings;
public MainWindow()
{
InitializeComponent();
strings = new ObservableCollection<string>();
grid.DataContext = strings;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
strings.Add("new value");
}
绑定集合时,在有值的情况下可见Rectangle,而在集合为空时则不可见.但是,如果集合为空,而我在运行时添加了一个值,则不会出现Rectangle(甚至不会触发转换器的Convert方法).我是否缺少某些东西,或者只是想问太多IValueConverter?
When the collection is bound, the Rectangle is visible when there are values and not when the collection is empty. However, if the collection is empty and I add a value at runtime, the Rectangle does not appear (the converter's Convert method isn't even fired). Am I missing something or just trying to ask too much of IValueConverter?
推荐答案
好的,所以这就是我使用MultiValueConverter
OK, so here's how I got around the problem using a MultiValueConverter
转换器现在看起来像:
public object Convert(
object[] values,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
ObservableCollection<string> strings =
values[0] as ObservableCollection<string>;
if (strings == null || !strings.Any())
return Visibility.Collapsed;
else
return Visibility.Visible;
}
public object[] ConvertBack(
object value,
Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
XAML现在看起来像:
And the XAML now looks like:
<Rectangle Height="100" Width="200" Fill="CornflowerBlue">
<Rectangle.Visibility>
<MultiBinding Converter="{StaticResource converter}">
<Binding Path="."/>
<Binding Path="Count"/>
</MultiBinding>
</Rectangle.Visibility>
</Rectangle>
C#保持不变:)
这篇关于WPF转换器和ObservableCollections的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!