//前台:
<ComboBox Name="combobox" Width="120" Height="30"/>
//后台:
public test5()
{
InitializeComponent(); Dictionary<int, string> mydic = new Dictionary<int, string>()
{
{1,"a"},
{2,"b"},
{3,"c"}
};
combobox.ItemsSource = mydic;
combobox.SelectedValuePath = "Key";
combobox.DisplayMemberPath = "Value";
}
ItemsSource 指定comboBox的数据源,可以是字典,list等任何形式的数据集合
SelectedValuePath 表示每个item的的实际值,DisplayMemberPath 表示每个item的显示值http://zhidao.baidu.com/link?url=EbB0OVjShh9Ua2rfy8jcAF1Q1F5tp8o0mDiw6rAsT4wz7FhKpeUYUf21MeEiadc2-U7eBur-zNwRFJS3AuADjq
<Window.Resources>
<DataTemplate x:Key="CbbBook">
<ComboBox Width="80" x:Name="BookCbb" Margin="-10,0,-10,0" ItemsSource="{Binding Path=books}" SelectedValuePath="bookid" DisplayMemberPath="bookname" ></ComboBox>
</DataTemplate>
</Window.Resources>
<Grid>
<DataGrid Name="dataGrid" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn MinWidth="150" Header="NAME" Binding="{Binding Path=name }" />
<DataGridTextColumn MinWidth="150" Header="ID" Binding="{Binding Path=id }" />
<DataGridTemplateColumn MinWidth="84" Header="书" CellTemplate="{StaticResource CbbBook}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
后台
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
} void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
List<stu> stu = new List<stu>();
stu row1 = new stu();
row1.name = "书籍1";
row1.id = "1";
List<book> book1 = new List<book>();
book item1 = new book();
item1.bookid = "1";
item1.bookname = "书1";
book item2 = new book();
item2.bookid = "2";
item2.bookname = "书2";
book1.Add(item1);
book1.Add(item2); row1.books = book1; stu.Add(row1); dataGrid.ItemsSource = stu; } }
public class stu
{
public string name { get; set; }
public string id { get; set; }
public List<book> books { get; set; }
}
public class book
{
public string bookname { get; set; }
public string bookid { get; set; }
}
<DataGridTemplateColumn Header="N" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding BookCollection}" DisplayMemberPath="Name"></ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
现在我能把值绑到combobox上了,可是选中某一项后,鼠标再点击别的地方,conbobox里的值就会被清空,这是怎么回事啊