gpt4 book ai didi

wpf - EmptyListToVisibilityConverter

转载 作者:行者123 更新时间:2023-12-03 15:07:51 24 4
gpt4 key购买 nike

我正在尝试为 WPF 做一个“空列表到可见性转换器”。
这是一个 IValueConverter ,它接受一个对象(应该是一个列表),如果列表为空(或者如果传递的对象为 null )它应该返回 Visibility.Collapsed;如果列表不为空,则应返回 Visibility.Visibile;

我计划将其用于数据网格。计划是每当提供给 ItemsSource 的列表为空列表或 null 时,使数据网格不可见(折叠)。

<my:DataGrid 
Name="dataGridAuxiliaryTools"
Style="{StaticResource DataGridStyle}"
CellStyle="{StaticResource DataGridCellStyle}"
ColumnHeaderStyle="{StaticResource DataGridColumnHeaderStyle}"
ItemsSource="{Binding Path=Items}"
IsReadOnly="False"
Visibility="{Binding Path=Items,
Converter={StaticResource emptyListToVisibilityConverter}}"
</my:DataGrid>

我写了 EmptyListToVisibilityConverter 如下:
public class EmptyListToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (value == null)
{
return Visibility.Collapsed;
}
else if (value is IList<Object>)
{
if ((value as IList<Object>).Count == 0)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
}
else
{
return Visibility.Visible;
}
}

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

这在 Items 为 null 时效果很好,但是当 Items 作为 List 给出时它不起作用......我认为下面的代码不正确并且无法检测“值”是否是一个列表......任何提示?
if (value is IList<Object>)
{
if ((value as IList<Object>).Count == 0)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}

关于如何做到这一点的任何提示?

最佳答案

您不能将列表转换为 IList ,但您可以将其转换为 ICollection,然后使用 ICollection.Count:参见 http://devw.wordpress.com/2011/07/18/empty-list-visibility-converter/
public class EmptyListVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Visibility.Collapsed;
else
{
ICollection list = value as ICollection;
if (list != null)
{
if (list.Count == 0)
return Visibility.Collapsed;
else
return Visibility.Visible;
}
else
return Visibility.Visible;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{
throw new NotImplementedException();
}
}
<ListBox x:Name=”NameChoiceListBox”
ItemsSource=”{Binding NamesList}”
SelectedItem=”{Binding SelectedName, Mode=TwoWay}”
ItemTemplate=”{StaticResource DataTemplateNameChoice}”
Visibility=”{Binding NamesList, Converter={StaticResource EmptyListVisibilityConverter}}”>

关于wpf - EmptyListToVisibilityConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3790650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com