WPF ListBox显示由DataGrid创建的空行

问题描述 投票:0回答:2

我同时将DataGridListbox绑定到相同的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来解决此问题吗?

c# wpf data-binding datagrid listbox
2个回答
0
投票

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>

0
投票

这将在您的列表框中隐藏{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>
© www.soinside.com 2019 - 2024. All rights reserved.