2012-11-16 123 views
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); 
    } 
} 

UPDATE

這裏是我的代碼的來源。 http://blog.bdcsoft.com/developer-blog/2011/no-binding-for-you-a-listbox-selecteditems-behavior-solution/

回答

0

不能賦值給一個列表框的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,而應該是一個空列表。

+0

它是一種行爲。 http://blog.bdcsoft.com/developer-blog/2011/no-binding-for-you-a-listbox-selecteditems-behavior-solution/。然而,收集應該初始化:( – GorillaApe

+0

@Parhs。是的,它是一個行爲,是的,mathieu告訴你什麼是錯誤的。看到我張貼的示例代碼。乾杯 – Berryl

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

我更新了問題的鏈接。問題是它不工作,它does.But如果目標爲空,那麼我不知道如果可以從這個代碼創建一個新的實例我的意思是SelectedListOfItems,如果以某種方式創建null,並且不需要在行爲外手動創建實例 – GorillaApe

+0

@Parhs在目標代碼中有警衛爲空你是否得到一個錯誤?發佈錯誤如果是的話...... – Berryl

+0

不,我沒有得到錯誤我的意思是假設你有一個產品對象有一個偏好屬性是一個集合屬性是nullo然後代碼不會工作,因爲它是空的。我想知道在這種情況下是否可以創建一個新實例,以便它可以自動工作 – GorillaApe