2015-04-24 60 views
0

我有關於XAML中數據綁定的問題。我有我的對象的字典。現在在視圖中我想顯示在字典的第一個列表框鍵(這沒有問題),但在嵌套列表框中顯示該對象的值。字典中對象屬性的數據綁定

所以 - 我的代碼在XAML:

<ListBox ItemsSource="{Binding Dict}" Margin="0,0,171,0"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
       <TextBlock Text="{Binding Path=Key}" /> 
       <ListBox ItemsSource="{Binding Path=Value}"> 
        <ListBox.ItemTemplate> 
         <DataTemplate> 
          <StackPanel> 
           <TextBlock Text="{Binding Path=Key}" /> 
           <TextBlock Text="{Binding Path=Value}" /> <!-- HERE --> 
          </StackPanel> 
         </DataTemplate> 
        </ListBox.ItemTemplate> 
       </ListBox> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

從視圖模型的代碼如下:

public MainWindow() 
{ 
    InitializeComponent(); 
    t = new TestModel(); 
    t._dict = new Dictionary<string, Dictionary<string, myDrive>>(); 

    t._dict.Add("folder1", new Dictionary<string, myDrive>()); 
    t._dict["folder1"].Add("file1", new myDrive() { size = "71" }); 
    t._dict.Add("folder2", new Dictionary<string, test>()); 
    t._dict["folder2"].Add("file1", new myDrive() { size = "54" }); 
    t._dict["folder2"].Add("file2", new myDrive() { size = "30" }); 

    this.DataContext = t; 
} 

和代碼模型:

public Dictionary<string, Dictionary<string, myDrive>> _dict; 

public Dictionary<string, Dictionary<string, myDrive>> Dict 
{ 
    get 
    { 
     return this._dict; 
    } 
} 

和類myDrive很簡單:

public class myDrive 
{ 
    public string size = ""; 

    public string getSize() 
    { 
     return this.size; 
    } 
} 

我的目標是顯示參數的大小在文本框,所以我嘗試不同的方法,如:

<TextBlock Text="{Binding Path=Value.size}" /> 
<TextBlock Text="{Binding Path=Value[size]}" /> 
<TextBlock Text="{Binding Path=Value.getSize}" /> 

,但沒有運氣:(。只有當我像示例中那樣放置值時,才能看到輸出字符串:「AppName.myDrive」。

感謝您的任何幫助

回答

0

首先定義大小變量的屬性。您只能將Databind屬性設置爲變量。

public class myDrive 
{ 
    public string size = ""; 

    public string Size{get{return size;}} 
    public string getSize() 
    { 
     return this.size; 
    } 
} 

一旦做到這一點,你可以綁定像下面

<ListBox ItemsSource="{Binding Dict}" Margin="0,0,171,0"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
       <TextBlock Text="{Binding Path=Key}" /> 
       <ListBox ItemsSource="{Binding Path=Value}"> 
        <ListBox.ItemTemplate> 
         <DataTemplate> 
          <StackPanel> 
           <TextBlock Text="{Binding Path=Key}" /> 
           <TextBlock Text="{Binding Path=Value.Size}" /> 
          </StackPanel> 
         </DataTemplate> 
        </ListBox.ItemTemplate> 
       </ListBox> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

是的,現在的功能謝謝:) –