在WPF中,如何在ComboBox中放置DataGrid以显示多个列?像下面这样的东西似乎没有做任何事情:
<ComboBox>
<ItemsPanelTemplate>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding customerName}" />
<DataGridTextColumn Binding="{Binding billingAddress}" />
</DataGrid.Columns>
</DataGrid>
</ItemsPanelTemplate>
</ComboBox>
答案 0 :(得分:11)
好的,如果我理解你有一个List<Customer>
的列表,列表列表将被绑定到ComboBox,并且每个子列表都绑定到DataGrid
示例:
的Xaml:
<Window x:Class="WpfApplication13.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Name="UI">
<Grid DataContext="{Binding ElementName=UI}">
<ComboBox DataContext="{Binding ComboItems}" Height="27" VerticalAlignment="Top" >
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" ColumnWidth="150" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding CustomerName}" />
<DataGridTextColumn Header="Address" Binding="{Binding BillingAddress}" />
</DataGrid.Columns>
</DataGrid>
</ComboBox>
</Grid>
</Window>
代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private ObservableCollection<Customer> _comboItems = new ObservableCollection<Customer>();
public MainWindow()
{
InitializeComponent();
ComboItems.Add(new Customer { CustomerName = "Steve", BillingAddress = "Address" });
ComboItems.Add(new Customer { CustomerName = "James", BillingAddress = "Address" });
}
public ObservableCollection<Customer> ComboItems
{
get { return _comboItems; }
set { _comboItems = value; }
}
}
public class Customer : INotifyPropertyChanged
{
private string _customerName;
private string _billingAddress;
public string CustomerName
{
get { return _customerName; }
set { _customerName = value; RaisePropertyChanged("CustomerName"); }
}
public string BillingAddress
{
get { return _billingAddress; }
set { _billingAddress = value; RaisePropertyChanged("BillingAddress"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
结果:
答案 1 :(得分:0)
<ComboBox Width="150" Height="30" Name="cb">
<ComboBox.ItemTemplate>
<DataTemplate>
<DataGridRow DataContext="{Binding}" Height="30" Width="150">
<DataGridRow.Template>
<ControlTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="5"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding customerName}" Margin="2"></TextBlock>
<Border BorderBrush="Black" BorderThickness="1" Grid.Column="1" Margin="2"></Border>
<TextBlock Grid.Column="2" Text="{Binding billingAddress}" Margin="2"></TextBlock>
</Grid>
</ControlTemplate>
</DataGridRow.Template>
</DataGridRow>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
答案 2 :(得分:-2)
对于其他寻找此问题的人,我找到了一个实现here。