从列表的行为创建实例

时间:2012-11-16 12:16:46

标签: c# wpf mvvm

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

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/

2 个答案:

答案 0 :(得分:1)

这可能比你现在想象的要容易,因为mathieu说为什么你的代码不起作用。尝试类似下面的代码。

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)
}

答案 1 :(得分: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方法。

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