[英]C# - Listbox not updated when an entry is added to the list in a seperate thread
[英]ListBox not updated when items added to data source
我有一个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>
在文本框中按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;
}
基本上在输入命令后,ObservableCollection将成功更新,但是列表框中的项目保持不变。
有任何想法吗?
您这里会有一个问题-搜索后,您将覆盖“ MyList”对象。 因此,一旦过滤,就无法取消过滤。 您应该研究使用CollectionViewSource 。
您需要实现INotifyPropertyChanged,在MyList的setter中,您将通知UI属性已更改。 这是一个例子:
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.