2012-04-18 73 views
0

我有一個簡單的窗口與列表框和標籤。我想將Label.Text綁定到ListBox,使其成爲Label中顯示的所選項之後的下一個ListBox項。 我試圖用multibinding用這樣的轉換器:WPF綁定到一個ListBox.Items

<Label> 
     <MultiBinding Converter="{StaticResource myConverter}"> 
      <Binding ElementName="lbox" Path="Items"/> 
      <Binding ElementName="lbox" Path="SelectedIndex"/> 
     </MultiBinding>--> 
</Label>  

public class MyConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
     object[] items = values[0] as object[]; 
     int index = (int)(values[1]) + 1; 
     return (items[index]).ToString(); 

    } 
    ..... 
} 

但它不工作。問題是我無法獲取ListBoxItems的數組。請你能幫助我嗎?

+0

嘗試使用SelectedIndex的,而不是在的SelectedItem你MultiBinding。 (請注意,即使這個代碼工作,這個代碼也非常脆弱。) – Alan 2012-04-18 21:03:43

回答

2

好吧,這裏有幾個錯誤。

  1. 在嘗試從陣列中取出某些東西之前,您沒有檢查索引值。如果沒有選擇會發生什麼,或者如果他們選擇最後一行會發生什麼?

  2. 調用列表框項的ToString()方法會給你「System.Windows.Controls.ListBoxItem:項目的文本」

  3. 最後,也許是最直接回答你的問題,是一個事實,即Items屬性不是一個對象[],而是一個ItemsCollection。您的代碼應該是這樣的:

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
        System.Windows.Controls.ItemCollection items = values[0] 
             as System.Windows.Controls.ItemCollection; 
    
        int index = (int)(values[1]) + 1; 
    
        ... 
    } 
    
1

您的代碼片段正確嗎?它在我看來你想SelectedIndex而不是SelectedValue(如果我已經正確理解你的問題)。 也就是說,

<Label> 
     <MultiBinding Converter="{StaticResource myConverter}"> 
      <Binding ElementName="lbox" Path="Items"/> 
      <Binding ElementName="lbox" Path="SelectedIndex"/> 
     </MultiBinding> 
</Label> 

注意,至少你應該在你的轉換器的一些錯誤檢查,以檢查你的計算指標仍處於範圍。

+0

你是對的,我將SelectedItem和SelectedIndex混合起來。但這只是代碼中的一個錯誤,並不能解決問題。問題是我無法獲得listboxItes數組。對象[]項目始終爲空值。 – 2012-04-19 06:15:16

+0

我想說你應該看看@ExitMusic給出的答案,這個答案在幫助你非常全面。 – 2012-04-19 08:35:34