2014-04-24 21 views
0

最近,我遇到了一個問題(可能是重要的提:我創建一個地鐵 APP):地鐵應用程序數據綁定到ObservableDictionary(或其他類型的集合)

我創建了一個ObservableDictionary之間的數據綁定(或一個詞典,或一個ObservableCollection<KeyValuePair<string,string>>)和一個GridView。 每個GridView項目包含綁定到每個Dictonary對的Key和Value的兩個Textblock。 但是,字典中的項目數完全一樣多,但這些框不包含任何文本。

奇怪的事情: 時不受Text={Binding Key}Text={Binding Value} 結合,但使用Text={Binding}顯示文本作爲一個希望它([someKey,someValue中])。

一些代碼(減少到要領):

private ObservableDictionary _someDictionary=new ObservableDictionary(); 
public ObservableDictionary SomeDictionary { 
    get { return _someDictionary; } 
    set { _someDictionary = value; } 
} 

public SomePage() { 
    this.InitializeComponent();    
    SomeDictionary.Add("TestKey", "TestValue"); 
    SomeDictionary.Add("TestKey2", "TestValue2"); 
    SomeDictionary.Add("TestKey3", "TestValue3"); 
} 

WPF:

<Page 
x:Class="TestView.Settings" 
DataContext="{Binding RelativeSource={RelativeSource Self}}" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Grid> 
     <GridView ItemsSource="{Binding Path=SomeDictionary}"> 
      <GridView.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <TextBlock Name="Key" Text="{Binding Path=Key}" /> 
         <TextBlock Name="Value" Text="{Binding Path=Value}" /> 
        </StackPanel> 
       </DataTemplate> 
      </GridView.ItemTemplate> 
     </GridView> 
    </Grid> 
</Page> 

有沒有人有一個想法,這裏有什麼問題?

感謝提前:)

回答

0

對於沒有起伏頭痛太長的時間,我決定寫我自己的小泛型類擴展ObservableCollection包含一些關鍵值的元素。 對於小型需求來說,這遠遠不夠。它的屬性可通過使用{Binding Path=Key}{Path=Value}進行綁定。

也許這將是爲別人有用:

using System.Collections.ObjectModel; 

namespace MyNamespace{ 
    public class BindableValuePairList<TK,TV> : 
     ObservableCollection<ValuePair<TK,TV>> { } 

    public class ValuePair<TK,TV> { 
     public ValuePair (TK key, TV value) { 
      Key = key; 
      Value= value; 
     } 

     public TK Key { get; set; } 

     public TV Value { get; set; } 
    } 
} 
-1

n您必須從DataTemplate中

<TextBlock Name="Key" Text="{Binding Key}" /> 
<TextBlock Name="Value" Text="{Binding Value}" /> 

綁定隨着Path=Key您綁定的文本框中的一個對象的名稱主要內容刪除路徑不是收藏中的關鍵。

而且您還必須將StackPanel綁定到字典的KeyValuePair,因爲Dictionary的枚舉符返回KeyValuePair

它應該是這樣的:

<StackPanel Orientation="Horizontal" DataContext={Binding}> 
+0

這也不起作用。這是我第一次嘗試,但它顯示相同的結果:沒有文本: -/ – Malte

+0

我使用創建這樣一個應用程序時由.Net提供的'ObservableDictionary:IObservableMap '。我也嘗試了一個ObservableCollection以及一個普通的Dictionary – Malte

相關問題