簡體   English   中英

將項目添加到數據源時,列表框未更新

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM