在WPF中获取空组合框下拉列表

时间:2018-07-23 10:26:06

标签: wpf datagrid

我正在尝试在“网格”列中填充下拉列表,但该列表为空。网格列的定义如下:

                <DataGridTemplateColumn  Header="Voucher Type" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding VoucherType}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox SelectedItem="{Binding VoucherType}" ItemsSource="{Binding Path=DataContext.VTypes, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>

上下文类的源定义如下:

        public static ObservableCollection<string> VType { get; } = new ObservableCollection<string>()
    {
        "Journal Voucher",
        "Cash Received Voucher",
        "Cash Payment Voucher",
        "Bank Received Voucher",
        "Bank Payment Voucher",
    };

有人可以指出我在做什么吗?

谢谢。

1 个答案:

答案 0 :(得分:-1)

这是简单的代码,说明如何在DataGrid中添加组合框。

Xaml代码:

<Grid>
    <DataGrid Margin="5" ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Capital" Binding="{Binding Capital}"/>
            <DataGridTextColumn Header="Time Zone" Binding="{Binding TimeZone}"/>
            <DataGridTemplateColumn Header="Cities" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Margin="2" ItemsSource="{Binding Cities}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

private ObservableCollection<State> states = new ObservableCollection<State>();
   public MainWindow()
    {
        InitializeComponent();

        states.Add(new State()
        {
            Name = "Maryland",
            Capital = "Annapolis",
            TimeZone = "Eastern",
            Cities = new ObservableCollection<string>() { "Frederick", "Baltimore", "Rockville"}
        });

        DataContext = states;
    }
}

型号:

 public class State
{
    public string Name
    { get; set; }

    public string TimeZone
    { get; set; }

    public string Capital
    { get; set; }

    public ObservableCollection<string> Cities
    { get; set; }
}

希望此代码对您有所帮助。