当我尝试在DataGrid中使用ComboBox时,我没有看到列表中用于填充ComboBox的任何项目。
当我使用StackPanel而不是DataGrid时,类似的实现工作。我想我在装订中遗漏了一些东西?
<Window x:Class="Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Demo"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="800">
<Grid Margin="10">
<DataGrid Name="dgRecords" ItemsSource="{Binding Records}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Number">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
IsEditable="True"
Width="120"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
Text="{Binding NewItem, UpdateSourceTrigger=LostFocus}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
namespace Demo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// List which populates DataGrid.
/// </summary>
private List<MyRecord> _records = new List<MyRecord>();
/// <summary>
/// List which populates ComboBox.
/// </summary>
private List<string> _items = new List<string>()
{
"One",
"Two",
"Three",
"Four",
"Five",
};
private string _selectedItem;
public class MyRecord
{
public string Number { get; set; }
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
_records.Add(new MyRecord() { Number = "One" });
_records.Add(new MyRecord() { Number = "Two" });
}
public IEnumerable Records
{
get { return _records; }
}
public IEnumerable Items
{
get { return _items; }
}
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
}
}
public string NewItem
{
set
{
SelectedItem = value;
// Set SelectedItem as Window Title.
this.Title = "Selected: " + SelectedItem;
}
}
}
}
答案 0 :(得分:0)
添加元素绑定以指向正确的DataContext。默认情况下,它将DataContext作为MyRecord,因为它是一行datagrid。请参阅下面的代码。
<Grid Margin="10">
<DataGrid Name="dgRecords" ItemsSource="{Binding Records}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Number">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
IsEditable="True"
Width="120"
ItemsSource="{Binding DataContext.Items, ElementName=dgRecords}"
SelectedItem="{Binding SelectedItem}"
Text="{Binding NewItem, UpdateSourceTrigger=LostFocus}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>