wpf 使用 C# 为 DataGrid 创建 ItemTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15582166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:16:29  来源:igfitidea点击:

Creating ItemTemplate for DataGrid with C#

wpfwpf-controlswpfdatagrid

提问by wpf_starter

Here is the XAML. I want to do the same thing with C#.

这是 XAML。我想用 C# 做同样的事情。

<DataGrid x:Name="myDataGrid">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Address">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Address}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Please help.

请帮忙。

回答by kmatyaszek

If you want to create DataTemplatein code you should use FrameworkElementFactory(msdn).

如果要DataTemplate在代码中创建,则应使用FrameworkElementFactory( msdn)。

XAML:

XAML:

<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False" Loaded="myDataGrid_Loaded">
    <DataGrid.Columns>
        <DataGridTemplateColumn x:Name="templateColumnAddress" Header="Address" />
    </DataGrid.Columns>
</DataGrid>

Code-behind:

代码隐藏:

public void myDataGrid_Loaded(object sender, EventArgs e)
{
    FrameworkElementFactory tbHolder = new FrameworkElementFactory(typeof(TextBox));
    tbHolder.SetBinding(TextBox.TextProperty, new Binding("Address"));          
    var dataTemplate = new DataTemplate();
    dataTemplate.VisualTree = tbHolder;
    dataTemplate.DataType = typeof(DataGridTemplateColumn);
    templateColumnAddress.CellTemplate = dataTemplate;
}