WPF以编程方式创建组合框不显示项目

时间:2018-03-19 09:36:38

标签: c# .net wpf

我正在尝试从后面的代码创建DatagridComboBoxColumn。如何将其正确链接到ElementStyleEditingElementStyle

我正在努力创造这个:

<DataGridComboBoxColumn Width="*" ElementStyle="{StaticResource ComboBoxElementStyle}" EditingElementStyle="{StaticResource ComboBoxEditingElementStyle}" />

创建了这个: enter image description here

来自:

private List<AppSettingsElement> appSettingsComboBoxList = new List<AppSettingsElement>();
...
private DataGridComboBoxColumn CreateComboValueColumn()
{
    DataGridComboBoxColumn column = new DataGridComboBoxColumn();
    column.ElementStyle = Resources["ComboBoxElementStyle"] as Style;
    column.EditingElementStyle = Resources["ComboBoxEditingElementStyle"] as Style;
    return column;
}

...
AppSettingsDropDowns.ItemsSource = appSettingsComboBoxList;
...
public class AppSettingsElement : ComboItem0
{
    public string Comment { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
    public string Type { get; set; }
    public List<ComboItem> ComboItems { get; set; }
}
public class ComboItem
{
    public string ID { get; set; }
    public string Text { get; set; }    

    public override string ToString()
    {
        return Text;
    }
}

哪个不显示comboBox:

enter image description here

我想要链接的样式:

<!-- ComboBox element and editing style -->
<Style x:Key="ComboBoxElementStyle" TargetType="{x:Type ComboBox}">
    <Setter Property="ItemsSource" Value="{Binding ComboItems}"/>
    <Setter Property="SelectedValue" Value="{Binding Value}" />
    <Setter Property="DisplayMemberPath" Value="Text"/>
    <Setter Property="SelectedValuePath" Value="ID" />
</Style>
<Style x:Key="ComboBoxEditingElementStyle" TargetType="{x:Type ComboBox}">
    <Setter Property="ItemsSource" Value="{Binding ComboItems}"/>
    <Setter Property="SelectedValue" Value="{Binding Value}" />
    <Setter Property="DisplayMemberPath" Value="Text"/>
    <Setter Property="SelectedValuePath" Value="ID" />
</Style>

1 个答案:

答案 0 :(得分:1)

首先给你的列命名,如下所示: column.Name =“myColumn”

然后尝试这样的事情:

  List<ComboData> ListData = new List<ComboData>();
  ListData.Add(new ComboData { Id = "1", Value = "One" });
  ListData.Add(new ComboData { Id = "2", Value = "Two" });
  ListData.Add(new ComboData { Id = "3", Value = "Three" });
  ListData.Add(new ComboData { Id = "4", Value = "Four" });
  ListData.Add(new ComboData { Id = "5", Value = "Five" });

 myColumn.ItemsSource = ListData;
 myColumn.DisplayMemberPath = "Value";
 myColumn.SelectedValuePath = "Id";
 myColumn.SelectedValue = "2";

ComboData看起来像:

public class ComboData
{ 
 public int Id { get; set; } 
 public string Value { get; set; } 
}

现在您的列表已准备就绪,最后在您的代码中应用如此;

column.ItemsSource = ListData.ToList();