簡體   English   中英

從帶有復選框的列表框中獲取選定的項目

[英]Get selected items from a list box with check boxes

一個帶有復選框的列表框(我刪除了與對齊方式,寬度,邊距無關的部分):

<ListBox  
ItemsSource ="{Binding SItemCollection}"     
<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox Content="{Binding Path=Item.Code}" IsChecked="{Binding IsChecked}"/>
    </DataTemplate>
</ListBox.ItemTemplate>

我在ViewModel中有一個SItem類,它存儲兩個字段-從緩存中獲取的CachedStr和表示是否已檢查該項的布爾值IsChecked布爾值(CachedStr對象也具有多個字段(名稱,代碼等),我已經選擇顯示代碼):

public class SItem : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public CachedStr Item { get; set; }
        private bool _isChecked;
        public bool IsChecked
        {
            get { return _isChecked; }
            set
            {
                _isChecked = value;
                NotifyPropertyChanged("IsChecked");
            }
        }

        protected void NotifyPropertyChanged(string strPropertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
        }

有一個SItems的集合(SItemCollection),它在我的ListBox中填充了項,其中的某些項已被選中。 該集合在SItem類之外,在我的視圖模型中。 我還具有一組應在ListBox中可用的所有項目(AvailableSItems),以及一開始應進行檢查的一組項目(ItemsToBeTicked)。 這兩組包含CachedStr類型的對象。 通過使用這些集合,我得到了SItemCollection:

public ObservableCollectionEx<SItem> SItemCollection
    {
        get
        {
            ObservableCollectionEx<SItem> strItems = new ObservableCollectionEx<SItem>();
            this.AvailableSItems.ForEach(p =>
            {
                SItem item = new SItem();
                item.Item = p;
                item.IsChecked = false;
                strItems.Add(item);
            });

            strItems.ForEach(p =>
             {
                 if (this.ItemsToBeTicked.Contains(p.Item))
                 {
                     p.IsChecked = true;
                 }
                 else p.IsChecked = false;
             }
             );
            return strItems;
        }
    }

上述代碼有效。 但是我還需要一種方法來獲取所有已打勾項目的最終集合(例如,在按下按鈕之后),這就是我遇到的問題。 勾選或取消勾選時,我會收到通知。

該代碼當前在get塊中創建該集合的新實例。 必須對此進行更改,否則,每次調用get塊時,都會還原在UI中所做的更改。

獲取當前在get塊中的代碼,將其提取到一個方法中,然后使用該方法的返回值設置SItemCollection屬性。

例如在構造函數中:

SItemCollection = CreateInitialCollection();

並將該財產簡化為:

public ObservableCollectionEx<SItem> SItemCollection 
{
    get
    {
        return _sitemCollection;
    }
    set
    {
        if (_sitemCollection!= value)
        {
            _sitemCollection= value;
            RaisePropertyChanged("SItemCollection");
        }
    }
}
ObservableCollectionEx<SItem> _sitemCollection;

解決此問題后(並且如果綁定到SItemIsChecked屬性有效),則可以使用Linq表達式:

var checkedItems = SItemCollection.Where(item => item.IsChecked == true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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