我用下面的代碼:如何綁定一個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 ?!
您需要將您的窗口的DataContext設置爲數據綁定工作的實例。你可以在'this.DataContext = this;'的構造函數中做到這一點,因爲你在本地綁定窗口。你應該在數據綁定時檢查你的輸出窗口,你可以看到爲什麼數據綁定失敗的一些小細節。 –