Search code examples
c#wpfdata-bindingdatagridlistbox

WPF ListBox showing empty row created by DataGrid


I have both DataGrid and Listbox binded to the same 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"/>

The problem is DataGrid allowing adding items (I want to keep this functionality) causes ListBox to display an empty row aswell. I don't want my ListBox to display this empty row at the end.

Can I somehow modify my ListBox to fix this?


Solution

  • This will hide the {NewItemPlaceholder} item in your ListBox:

                <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>