如何使用DataTable绑定到DataGrid在DataGrid中创建组合框列? [英] How do I create a combobox column in a DataGrid using a DataTable to Bind to the DataGrid?

查看:77
本文介绍了如何使用DataTable绑定到DataGrid在DataGrid中创建组合框列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UserControl中有一个DataGrid。 我正在使用DataTable为DataGrid创建数据元素,然后将DataTable绑定到DataGrid的ItemsSource。 我需要DataGrid中的一个列是一个Combobox。 在创建
DataTabe时,我将组合框的列设置为ObservableCollection< string>。 当我运行应用程序时,我得到了Combobox项目,但它没有值。 下面是一些示例代码。

I have a DataGrid in a UserControl.  I am using a DataTable to create the data elements for the DataGrid then Bind the DataTable to the DataGrid's ItemsSource.  I need one of the columns in the DataGrid to be a Combobox.  When creating the DataTabe I set the column for the combobox as an ObservableCollection<string>.  When I run the application I get the Combobox item but it has no values.  Here is some sample code.

我正在使用MVVM方法。

I am using the MVVM methodology.

DataGrid:

<DataGrid IsReadOnly="True" Name="dtSDGrid" HorizontalAlignment="Left" VerticalAlignment="Top" 
                      Height="187" Margin="30,100,0,0" BorderThickness="1" BorderBrush="Black" 
                      FontFamily="Arial" FontSize="16" AutoGenerateColumns="False" HorizontalScrollBarVisibility="Auto"
                      VerticalScrollBarVisibility="Auto" CanUserAddRows="False" CanUserDeleteRows="False"
                      CanUserReorderColumns="False" CanUserResizeColumns="True" CanUserResizeRows="False"
                      CanUserSortColumns="False" ItemsSource="{Binding SourceFieldsDataTable}"
                      SelectionMode="Extended" >

</DataGrid>

以下是我为ComboBox创建DataGrid列的方法:

Here is how I am creating the DataGrid column for the ComboBox:

<DataGrid.Columns>
    <DataGridTextColumn Header="Source Field Name" Binding="{Binding SourceFieldName}" Width="200" />
     <DataGridTextColumn Header="Description" Binding="{Binding SourceFieldDescription}" Width="150"/>

<DataGridTemplateColumn Header="Type" Width="100">
     <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
            <ComboBox ItemsSource="{Binding Path=DataContext.FieldTypeList, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
DisplayMemberPath="FieldTypeValue" SelectedValuePath="FieldTypeValue"
SelectedItem="{Binding DataContext.FieldTypeName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

</DataGrid.Columns>

以下是我创建DataTable的方法:

Here is how I am creating the DataTable:

private void InitializeMappingMetadata()
        {
            ObservableCollection<MappingDataMetadata> mappingMetadata = new ObservableCollection<MappingDataMetadata>();
            ObservableCollection<string> sourceFieldTypeList = new ObservableCollection<string>();
            string _infoText = string.Empty;
            

            _infoText = "Setup the mapping file parameters.";

            sourceFieldTypeList.Add("Boolean");
            sourceFieldTypeList.Add("Date");
            sourceFieldTypeList.Add("Date/Time");
            sourceFieldTypeList.Add("Float");
            sourceFieldTypeList.Add("Integer");
            sourceFieldTypeList.Add("Name");
            sourceFieldTypeList.Add("Text");
            sourceFieldTypeList.Add("Time");

            try
            {
                mappingMetadata.Add(new MappingDataMetadata
                {
                    MappingSourceMetadata = null,
                    MappingTargetMetadata = null,
                    MappingViewInfo = _infoText,
                    FieldTypeValue = "Text",
                    FieldTypeName = "Text",
                    FieldTypeList = sourceFieldTypeList
                });
                
                MappingMetadata = mappingMetadata;
                RaisePropertyChanged("MappingMetadata");
            }
            catch (Exception exQuery)
            {
                string strMsg;


                strMsg = "InitializeMappingMetadata: Error, '" + exQuery.Message + "', has occurred.";
                System.Windows.MessageBox.Show(strMsg);
            }
        }

如何正确填充组合框?

推荐答案

你好Cassfutbol,

Hi Cassfutbol,

根据你的描述,你想将datatable绑定到datagrid,并且datagrid中有一个组合框,  combobox的itemsource是ObservableCollection< string>。我想你在Combobox中可能有一些问题,如果你想在组合框中显示价值,
你只需要为组合框添加itemsource和selecteditem,我做一个你可以看看的样本,然后修改你的代码。

According to your description, you want to bind datatable to datagrid, and there is one combobox in datagrid, combobox's itemsource is ObservableCollection<string>. I think you may have some issue in Combobox, if you want to display value in combobox, you just add itemsource and selecteditem for combobox, I do one sample that you can take a look, then modify your code.

 <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding dt}">
            <DataGrid.Columns>
                <DataGridTextColumn
                    Width="100"
                    Binding="{Binding Id}"
                    Header="Id" />
                <DataGridTextColumn
                    Width="100"
                    Binding="{Binding Name}"
                    Header="Name" />
                <DataGridTemplateColumn Width="100" Header="Gender">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox ItemsSource="{Binding Path=DataContext.stringlist, RelativeSource={RelativeSource AncestorType=local:Window28}}" SelectedItem="{Binding Gender}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>


 public partial class Window28 : Window,INotifyPropertyChanged
    {
        private DataTable _dt;
        public DataTable dt
        {
            get { return _dt; }
            set
            {
                _dt = value;
                RaisePropertyChanged("dt");

            }
        }

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

        public Window28()
        {
            InitializeComponent();

            dt = new DataTable();
            dt.Columns.Add("Id", typeof(Int32));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Gender", typeof(string));

            dt.Rows.Add(1,"cherry", "Male");
            dt.Rows.Add(2, "Mattew", "Female");

            stringlist = new ObservableCollection<string>() {"Male","Female","No Know" };

            this.DataContext = this;
        }
         
        public event PropertyChangedEventHandler PropertyChanged;

       
        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

最好的问候,

Cherry


这篇关于如何使用DataTable绑定到DataGrid在DataGrid中创建组合框列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆