我用下面的代码:如何绑定一个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;'的构造函数中做到这一点,因为你在本地绑定窗口。你应该在数据绑定时检查你的输出窗口,你可以看到为什么数据绑定失败的一些小细节。 –