0

我有一种行为来支持列表框中的 selectedItems。这是代码的一部分。如果目标又名AssociatedObject.SelectedItems为空,是否有办法 创建它的实例?我尝试的一切都失败了...

void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    //Need to unsubscribe from the events so we don't override the transfer
    UnsubscribeFromEvents();
         
    //Move items from the selected items list to the list box selection
    Transfer(SelectedItems as IList,  AssociatedObject.SelectedItems);
         
    //subscribe to the events again so we know when changes are made
    SubscribeToEvents();
}

public static void Transfer(IList source,  IList target)
{
    if (source == null || target == null)
    {
        return;
    }
         
    target.Clear();
         
    foreach (var o in source)
    {
       target.Add(o);
    }
}

更新

这是我的代码的来源。 http://blog.bdcsoft.com/developer-blog/2011/no-binding-for-you-a-listbox-selecteditems-behavior-solution/

4

2 回答 2

1

This might be easier than you think now that mathieu said why your code doesn't work. Try something like the code below.

HTH,
Berryl

void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Need to unsubscribe from the events so we don't override the transfer
UnsubscribeFromEvents();

//Move items from the selected items list to the list box selection
Transfer(SelectedItems as IList,  AssociatedObject);

//subscribe to the events again so we know when changes are made
SubscribeToEvents();
}

public static void Transfer(IList source,  ListBox lb)
{
    if (source == null || lb== null || !lb.SelectedItems.Any())
        return;
}
lb.SetSelectedItems(source)
}
于 2012-11-17T14:39:09.343 回答
0

您不能为 ListBox 的 SelectedItems 属性分配值,因为它是只读属性: http: //msdn.microsoft.com/en-us/library/system.windows.controls.listbox.selecteditems(v=vs. 110).aspx

[BindableAttribute(true)]
public IList SelectedItems { get; }

为此使用SetSelectedItems方法。

此外,ListBox 上的 SelectedItems 属性不应为空,而应为空列表。

于 2012-11-16T12:32:57.067 回答