2010-11-05 138 views
0

related question我問到綁定到由另一個屬性索引的數組的特定元素。提供的答案對於提供的示例代碼示例非常有效。WPF ListBox綁定項目源

我遇到麻煩的地方是我爲ListBox指定了一個ItemSource,並且當我遍歷它時,我在我的轉換器中獲得了一個DependencyProperty.UnsetValue。毫無疑問,這是我對綁定理解的一個問題。

我的列表框看起來像這樣:

<ListBox ItemsSource="{Binding Path=MyList}"> 
    <ListBox.Resources> 
     <local:FoodIndexConverter x:Key="indexConverter" /> 
    </ListBox.Resources> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock> 
       <TextBlock.Text> 
        <MultiBinding Converter="{StaticResource indexConverter}"> 
         <Binding Path="MyIndex" /> 
         <Binding Path="Fields" /> 
        </MultiBinding> 
       </TextBlock.Text> 
      </TextBlock> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

和後面的代碼看起來像這樣:

public MainWindow() 
{ 
    InitializeComponent(); 
    MyList.Add(new SomeData() { Fields = new object[] {"liver", "onions", "cake" } }); 
    MyList.Add(new SomeData() { Fields = new object[] {"liver", "onions", "candy" } }); 
    MyList.Add(new SomeData() { Fields = new object[] {"liver", "onions", "pie" } }); 

    DataContext = this; 
} 

MYLIST是一個列表。

MyIndex是一個int。

轉換器代碼是

public class FoodIndexConverter : IMultiValueConverter 
    { 
     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (values == null || values.Length != 2) 
       return null; 

      int? idx = values[0] as int?; 
      object[] food = values[1] as object[]; 

      if (!idx.HasValue || food == null) 
       return null; 

      return food[idx.Value]; 
     } 

     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

當我通過調試器在轉換器的代碼MyIndex(值[0])是DependencyProperty.UnsetValue步驟 - 對象陣列是我期望。

我假設它是一個綁定問題: 因爲它不知道MyIndex是什麼。

如果MyIndex是SomeData類的一個屬性,它可以像我期望的那樣工作,但它不是,它是類MainWindow的屬性,就像MyList一樣。

如何指定我對屬於我的DataContext而不是MyData列表的MyIndex屬性感興趣?

回答

1

它正在尋找ListBoxItem上的MyIndex屬性(在這種情況下是一個SomeData類),並且該屬性不存在。

將ElementName設置爲綁定到窗口名稱以使其在其他位置查找屬性。

<Binding ElementName=RootWindow, Path=DataContext.MyIndex /> 
+0

是的 - 太好了。像冠軍一樣工作。這是一個美好的一天 - 我學到了一些東西。 :) – itsmatt 2010-11-05 15:45:24