WPF:将DataGrid放在ComboBox中

dot*_*NET 5 wpf datagrid combobox

在WPF中,如何将DataGrid放在ComboBox中以显示多个列?像下面的东西似乎没有做任何事情:

<ComboBox>
    <ItemsPanelTemplate>
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding customerName}" />                 
                <DataGridTextColumn Binding="{Binding billingAddress}" />
            </DataGrid.Columns>
        </DataGrid>
    </ItemsPanelTemplate>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

sa_*_*213 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>
Run Code Online (Sandbox Code Playgroud)

码:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述


dot*_*NET 0

对于其他正在寻找此内容的人,我在这里找到了一个实现。