为什么这个组合框没有显示项目?

时间:2018-04-17 16:54:35

标签: c# wpf mvvm combobox

我正在编写一个导入实用程序,我希望用户能够从CSV上传,然后将列指向他们想要的列。

因此,为了做到这一点,我正在使用所有可能的列填充每个列的标题。

XAML

        <DataGrid x:Name="ImportTable" 
                  ItemsSource="{Binding displayTable}"
                  AutoGeneratingColumn="OnAutoGeneratingColumn"
                  AutoGenerateColumns="True"
                  CanUserAddRows="True" 
                  CanUserDeleteRows="True"
                  EnableColumnVirtualization="True"
                  EnableRowVirtualization="True"
                  MaxWidth="1300"
                  MaxHeight="600"
                  />

xaml.cs

    private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {

        var cb = new ComboBox();
        foreach (DataColumn test in (DataContext as EnterValueDialogViewModel).displayTable.Columns)
            Console.Out.WriteLine(test);

        cb.ItemsSource = (DataContext as EnterValueDialogViewModel).displayTable.Columns;
        e.Column.Header = cb;
    }

这样可以正确地打印出所有列,但实际上没有任何内容显示在组合框的

Empty Combobox

组合框现在可以在下拉列表中正确显示。但我无法得到它的selectedValue来设置。以下代码打印出selectedvalue是正确的,但它最初仍然填充为空白/未选择

        var cb = new ComboBox();
        cb.DisplayMemberPath = "ColumnName";
        cb.SelectedValue = e.PropertyName.ToString();
        cb.ItemsSource = (DataContext as EnterValueDialogViewModel).displayTable.Columns;
        Console.Out.WriteLine(cb.SelectedValue);
        e.Column.Header = cb;

2 个答案:

答案 0 :(得分:1)

您可以尝试设置组合框的DisplayMemberPath

    private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {

        var cb = new ComboBox();
        cb.DisplayMemberPath = "SomePropertyFromYourCollection";
        foreach (DataColumn test in (DataContext as EnterValueDialogViewModel).displayTable.Columns)
            Console.Out.WriteLine(test);

        cb.ItemsSource = (DataContext as EnterValueDialogViewModel).displayTable.Columns;
        e.Column.Header = cb;
    }

文档here

答案 1 :(得分:0)

您需要设置我认为的组合框的DisplayMemberPathSelectedValuePath

这些是您的数据文件中的列名。

看起来应该是这样的:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    var cb = new ComboBox();
    foreach (DataColumn test in (DataContext as EnterValueDialogViewModel).displayTable.Columns)
        Console.Out.WriteLine(test);

    cb.ItemsSource = (DataContext as EnterValueDialogViewModel).displayTable.Columns;
    cb.DisplayMemberPath = "Column1";
    cb.SelectedValuePath = "Column2";
    e.Column.Header = cb;
}   

如果有帮助,请告诉我。