简体   繁体   中英

ListBox not updated when items added to data source

I have a ListBox where items are filtered based on text entered in a textbox (and when enter is pressed):

<TextBox DockPanel.Dock="Top" Margin="0,0,0,20" Width="200" HorizontalAlignment="Left" Text="{Binding Path=FilterText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
   <TextBox.InputBindings>
      <KeyBinding Command="{Binding Path=FilterSearchCommand}" Key="Enter" />
   </TextBox.InputBindings>
</TextBox>
<ListBox DockPanel.Dock="Bottom" Name="lbItems" ItemsSource="{Binding Path=MyList, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel Width="{Binding ActualWidth, ElementName=lbItems}" Cursor="Hand" Margin="10,10,0,10" VerticalAlignment="Center" MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp">
            <TextBlock Text="{Binding Path=Title}"/>
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

When ENTER is pressed in the textbox, the following command is executed:

FilterSearchCommand = new RelayCommand(() => {
 MyList = new ObservableCollection < MyObject > (MyList.Where(x => x.Title.IndexOf(FilterText, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList());
});

public RelayCommand FilterSearchCommand {
 get;
}
public string FilterText {
 get;
 set;
}
public ObservableCollection < MyObject > MyList {
 get;
 set;
}

Basically on entering the command, the ObservableCollection is successfully updated, however the items in the list box remain unchanged.

Any ideas?

You are going to have a bit of an issue here - Upon a search, you will overwrite your 'MyList' object. So, once you filter, you cannot un-filter. You should look into using a CollectionViewSource .

You need to implement INotifyPropertyChanged, and in the setter of MyList you will notify the UI that the property is changed. Here's an example:

class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<MyObject> _myList;

    public ObservableCollection<MyObject> MyList
    {
        get { return _myList; }
        set
        {
            _myList = value; 
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM