我同时将DataGrid
和Listbox
绑定到相同的ObservableCollection
:
public ObservableCollection<Contact> contacts = new ObservableCollection<Contact>();
CntGrid.ItemsSource = contacts;
CntListBox.ItemsSource = contacts;
<DataGrid x:Name="CntGrid"
IsReadOnly="False"
CanUserAddRows="True"
CanUserDeleteRows="True"/>
<ListBox x:Name="CntListBox"/>
问题是DataGrid
允许添加项目(我想保留此功能),导致ListBox
也显示空白行。我不希望我的ListBox
在最后显示此空行。
我可以以某种方式修改我的ListBox
来解决此问题吗?
DataGrid中的空行是NewItemPlaceholder。与联系人的类型不同。因此,我建议使用转换器将其隐藏在ListBox中:
public class ObjectTypeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var t = parameter as Type;
if (value == null || t == null)
return false;
return t.IsAssignableFrom(value.GetType());
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
使用ListBoxItem样式中的该转换器检查项目的类型,如果类型不匹配,则将其隐藏:
<Window.Resources>
<local:ObjectTypeConverter x:Key="tc"/>
</Window.Resources>
<ListBox x:Name="CntListBox">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Converter={StaticResource tc}, ConverterParameter={x:Type local:Contact}}"
Value="False">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
这将在您的列表框中隐藏{NewItemPlaceholder}项目:
<ListBox x:Name="CntListBox">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="{x:Static CollectionView.NewItemPlaceholder}">
<Setter Property="UIElement.Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>