簡體   English   中英

從列表框中僅獲取一個選定的項目

[英]Getting Only one Selected Item from Listbox

我正在wpf中使用Listbox。我的問題是我只從listbox中獲得一個選定的項目。我想獲得所有選定的項目,但不知道如何實現? 請幫忙! 這是我的代碼:

<ListBox ItemsSource="{Binding Markets}" BorderThickness="0" Background="{x:Null}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Multiple" SelectedItem="{Binding SelectedItem}">
     <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" />
            </ItemsPanelTemplate>
     </ListBox.ItemsPanel>
     <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding}" Style="{DynamicResource CheckBoxStyle1}" Width="140" Margin="10"/>
            </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

這是我的viewmodel內容:

    private string _selectedItem;
    public List<string> Markets { get; set;}
    public SettingVM()
    {

        Markets = new List<string>();
        Markets.Add("United Kingdom");
        Markets.Add("Australia");
    }
    public string SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
            Set(() => SelectedItem, ref _selectedItem, value);
        }
    }     

您可以將SelectedItem listobx屬性直接綁定到視圖模型,但是不能將SelectedItems屬性綁定。

我使用一種行為來實現與委托命令(包括在Prism框架中)相關的行為

你的對象

class MyObject
{

}

行為

internal class MyObjectSelectionChangedToCommand
{

    public static readonly DependencyProperty SelectionCommandProperty =
        DependencyProperty.RegisterAttached("SelectionCommand", typeof(DelegateCommand<GridSelectionInfo<MyObject>>),
        typeof(ResourceCardGridSelectionChangedToCommand), new PropertyMetadata(null, OnSelectionCommandChanged));

    public static DelegateCommand<GridSelectionInfo<MyObject>> GetSelectionCommand(DependencyObject obj)
    {
        return (DelegateCommand<GridSelectionInfo<MyObject>>)obj.GetValue(SelectionCommandProperty);
    }

    public static void SetSelectionCommand(DependencyObject obj, DelegateCommand<GridSelectionInfo<MyObject>> value)
    {
        obj.SetValue(SelectionCommandProperty, value);
    }

    private static void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var tsci = new GridSelectionInfo<MyObject>
        {
            Added = e.AddedItems.Cast<MyObject>().ToList(),
            Removed = e.RemovedItems.Cast<MyObject>().ToList(),
            Selected = ((ListBox)sender).SelectedItems.Cast<MyObject>().ToList()
        };

        var cmd = GetSelectionCommand((DependencyObject)sender);
        cmd.Execute(tsci);
    }

    private static void OnSelectionCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var dg = d as ListBox;

        if (dg != null) dg.SelectionChanged += dg_SelectionChanged;
    }
}

public class GridSelectionInfo<T>
{
    public GridSelectionInfo()
    {
        Selected = new List<T>();
        Added = new List<T>();
        Removed = new List<T>();
    }

    public List<T> Added { get; set; }

    public List<T> Removed { get; set; }
    public List<T> Selected { get; set; }

    public override string ToString()
    {
        return string.Format("Added: {0}, Removed: {1}, Selected: {2}", Added.Count, Removed.Count, Selected.ToFormattedString());
    }
}

將視圖模型命令綁定到行為的XAML部分

<ListBox  ItemsSource="{Binding MyCollection}"
 resources:ResourceCardGridSelectionChangedToCommand.SelectionCommand="{Binding CmdObjectSelectionChanged}">
</ListBox>

然后,在視圖模型中,您只需要聲明以下命令

public DelegateCommand<GridSelectionInfo<MyObject>> CmdObjectSelectionChanged { get; private set; }

並創建它

CmdObjectSelectionChanged = new DelegateCommand<<GridSelectionInfo<MyObject>>(ExecuteSelect,CanExecuteSelect);

因此,每次列表框中的選擇更改時,您都將在GridSelectionInfo對象中包裝的執行委托中收到有關選定項目的所有信息。

也許這對你有幫助

您可以在ListBox.SelectedItems中找到它們。 使用foreach

foreach (ListItem li in listBox1.SelectedItems)
{
// your code here
}

您使用“ SelectedItem =” {Binding SelectedItem}“>”。 符合MSDN“獲取或設置當前選擇項中的第一項,或者如果選擇項為空,則返回null”

並且您需要將SelectedItems綁定到視圖模型中的列表。

在ListBox控件中,SelectedItems屬性為只讀,但是您可以添加執行此操作的行為,請參見以下答案: https : //stackoverflow.com/a/8369532/1431524

我有同樣的問題,當我綁定到SelectedItems時,該屬性在某些情況下沒有通知模型! 我結束了使用非持久屬性(“ Selected”)擴展我的實體,然后將此屬性綁定到CheckBox的IsCheched屬性。 在您的情況下,創建另一個局部類文件Market來擴展Market對象,添加一個新的bool屬性(例如Selected),然后在您的復選框中綁定此屬性:

<CheckBox Content="{Binding}" IsChecked="{Binding Selected}" Style="{DynamicResource CheckBoxStyle1}" Width="140" Margin="10"/>

暫無
暫無

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

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