2012-11-15 143 views
0

我有一個列表框我試圖用「metro」應用程序綁定數據。這是我的XAML:Windows 8列表框數據綁定

<ListBox x:Name="ImagesList" Margin="40" Grid.Row="1"> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Key}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox> 

而且我已經創建了一個源:

 List<KeyValuePair<string, string>> items = 
      new List<KeyValuePair<string, string>>(); 

     items.Add(new KeyValuePair<string, string>("a", "a")); 
     items.Add(new KeyValuePair<string, string>("b", "b")); 
     items.Add(new KeyValuePair<string, string>("c", "c")); 
     this.ImagesList.ItemsSource = items; 

我希望這在我的應用程序A,B創建文本列表和c

然而,相反,我收到我綁定的每個元素的以下文本:

System.Runtime.InteropServices.CLRKeyBaluePairOmpl'2[System.String, System.String] 

它看起來像它顯示的全名類型我綁定...我做錯了什麼?

回答

1

你需要一個Converter分配給Binding

蠟膏轉換爲XAML資源

<src:KeyValueConverter:Key="KeyConverter"/> 

添加綁定轉換器,以文本源

Text="{Binding Path=ItemsList, Converter={StaticResource KeyConverter}}" 

樣品轉換代碼

public class KeyValueConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var kvp = (KeyValuePair)value; 
     return kvp.Key; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0
+0

Mayank

+0

我打算將其標記爲答案,因爲我相信它適用於我的KVP示例。 – Liath

0

我的XAML也錯了,它應該是:

<ListBox x:Name="ImagesList" Margin="40" Grid.Row="1"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Value}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox>