C#WPF在DataGrid中添加控件

时间:2018-09-26 16:12:17

标签: c# wpf datagrid wpfdatagrid

我想在DataGrid中添加一些控件。

我有XML代码:

<DataGrid Name="dgCreateOperationsData" HorizontalScrollBarVisibility="Hidden"  HorizontalAlignment="Left" Height="214" Margin="2,170,0,0" VerticalAlignment="Top" Width="775" FontWeight="Bold" HeadersVisibility="None" SelectionMode="Single" Background="White"  CanUserAddRows="False" CanUserDeleteRows="False" ColumnWidth="100"/>

和以下代码:

OperationEntry opEntry = new OperationEntry();
opEntry.OperationName = new ComboBox() { Width = 50, ItemsSource = _operationList};
opEntry.Time = new TextBox() { Width = 50, Text = "" };
opEntry.Flow = new TextBox() { Width = 50, Text = "" };
opEntry.SysSpeed = new TextBox() { Width = 50, Text = "" };
opEntry.Pressure = new TextBox() { Width = 50, Text = "" };
opEntry.Torque = new TextBox() { Width = 50, Text = "" };
opEntry.Power = new TextBox() { Width = 50, Text = "" };
opEntry.Current = new TextBox() { Width = 50, Text = "" };

_operationEntryList.Add(opEntry);
dgCreateOperationsData.ItemsSource = _operationEntryList;

问题在于控件正在显示,但是控件类型可见,直到我双击它为止(见图片)

enter image description here

为什么会这样?以及如何删除这些标签?

2 个答案:

答案 0 :(得分:0)

下面是示例代码。您需要对其进行处理才能完成功能。 通过代码添加一条记录,要添加更多记录,只需在最后一行按Enter。它将自动将记录添加到集合中,您可以对数据进行任何操作。

查看-

<DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding CountryList}" BorderThickness="0" HorizontalAlignment="Left">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Country Name" Binding="{Binding CountryName}"/>
            <DataGridComboBoxColumn Header="City Name"/>
        </DataGrid.Columns>
    </DataGrid>

ViewModel-

    public ObservableCollection<CountryData> CountryList { get; set; }

        CountryList = new ObservableCollection<CountryData>();
        CountryList.Add(new CountryData { CountryName = "India" });

答案 1 :(得分:0)

您可以用DataGridTemplateColumns定义CellTemplates

...
dgCreateOperationsData.ItemsSource = _operationEntryList;
dgCreateOperationsData.AutoGeneratingColumn += (s, e) =>
{
    FrameworkElementFactory fe = new FrameworkElementFactory(typeof(ContentControl));
    fe.SetBinding(ContentControl.ContentProperty, new Binding(e.PropertyName));
    e.Column = new DataGridTemplateColumn()
    {
        CellTemplate = new DataTemplate() { VisualTree = fe }
    };
};