[英]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): 我有一个ListBox
,其中根据在文本框中输入的文本(以及按Enter时)过滤项目:
<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: 在文本框中按ENTER键时,将执行以下命令:
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. 基本上在输入命令后,ObservableCollection将成功更新,但是列表框中的项目保持不变。
Any ideas? 有任何想法吗?
You are going to have a bit of an issue here - Upon a search, you will overwrite your 'MyList' object. 您这里会有一个问题-搜索后,您将覆盖“ MyList”对象。 So, once you filter, you cannot un-filter. 因此,一旦过滤,就无法取消过滤。 You should look into using a CollectionViewSource . 您应该研究使用CollectionViewSource 。
You need to implement INotifyPropertyChanged, and in the setter of MyList you will notify the UI that the property is changed. 您需要实现INotifyPropertyChanged,在MyList的setter中,您将通知UI属性已更改。 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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.