2012-10-20 47 views
0

我用下面的代碼:如何綁定一個ComboBox通用字典使用XAML代碼

private Dictionary<string, string> GetNumber { get; set; } 
public ReportsLetterTra() 
{ 
    GetNumber = new Dictionary<string, string> 
          { 
           {"1", "First"}, 
           {"2", "Second"} 
          }; 

    InitializeComponent(); 
} 

XAML代碼:

<ComboBox 
     DisplayMemberPath="value" 
     SelectedValuePath="key" 
     ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}" 
     SelectedIndex="0" Name="cmbFromNumber" /> 

爲什麼不綁定GetNumber到cmbFromNumber?

更新:

我的完整代碼隱藏文件:

using System.Collections.Generic; 
using System.Windows; 

namespace WpfApplication20 
{ 
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : Window 
    { 
     public Dictionary<string, string> GetNumber { get; set; } 

     public Window1() 
     { 

      GetNumber = new Dictionary<string, string> 
            { 
             {"1", "First"}, 
             {"2", "Second"} 
            }; 
      InitializeComponent(); 

     } 
    } 
} 

我的完整XAML代碼:

<Window x:Class="WpfApplication20.Window1" Name="eportslettra" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <Grid Height="26"> 
     <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key" 
       ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}" 
       SelectedIndex="0" Name="cmbFromNumber" /> 
    </Grid> 
</Window> 

哪裏是我的錯嗎? 爲什麼不把GetNumber綁定到cmbFromNumber ?!

+0

您需要將您的窗口的DataContext設置爲數據綁定工作的實例。你可以在'this.DataContext = this;'的構造函數中做到這一點,因爲你在本地綁定窗口。你應該在數據綁定時檢查你的輸出窗口,你可以看到爲什麼數據綁定失敗的一些小細節。 –

回答

1

您的房產被標記爲private,使其成爲public。另外,請將您的ComboBox上的外殼更正爲ValueKey。第三,你的綁定表達式看起來無效,請仔細檢查。最後,它看起來像你的屬性是視圖的代碼隱藏文件的一部分。你可能會考慮MVVM設計模式。

更新

Window有 'eportslettra' 的Name,但你的綁定表達式使用ElementName 'reportslettra'。糾正其中一個。

+0

我用:public Dictionary GetNumber {get;組; }。但不在組合框中顯示數據。爲什麼? –

+0

答覆已更新。 – devdigital

+0

問題已更新。請檢查。 –

相關問題