0

我想只使用 C# 制作这个 XAML 模板:

<DataGrid AlternationCount="2" AutoGenerateColumns="False" Margin="6,78,9,47" Name="datagrid_Jobs">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Title, Mode=OneWay}" Header="Job" />
        <DataGridTextColumn Binding="{Binding Mode=TwoWay, Path=Score}" Header="Score" />
        <DataGridTemplateColumn Header="Perecent Complete">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Slider Margin="5" Maximum="100" Minimum="0" Value="{Binding Path=Score, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

我只想在 XAML 中定义网格,我想用 C# 制作整个模板。
我不知道从哪里开始。

4

2 回答 2

2

我认为你需要的只是在这个网站上检查它:

http://harishasanblog.blogspot.ca/2011/01/create-datagrid-in-wpf-using-code.html

于 2013-03-19T17:07:38.840 回答
0

您应该使用FrameworkElementFactory( msdn )。

XAML:

<DataGrid AlternationCount="2" AutoGenerateColumns="False" Margin="6,78,9,47" Name="datagrid_Jobs"
          Loaded="datagrid_Jobs_Loaded">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Title, Mode=OneWay}" Header="Job" />
        <DataGridTextColumn Binding="{Binding Mode=TwoWay, Path=Score}" Header="Score" />
        <DataGridTemplateColumn x:Name="pcColumn" Header="Perecent Complete" />
    </DataGrid.Columns>
</DataGrid>

代码隐藏:

public void datagrid_Jobs_Loaded(object sender, EventArgs e)
{
    FrameworkElementFactory sliderHolder = new FrameworkElementFactory(typeof(Slider));
    sliderHolder.SetBinding(Slider.ValueProperty, new Binding("Score") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
    sliderHolder.SetValue(Slider.MarginProperty, new Thickness(5));
    sliderHolder.SetValue(Slider.MaximumProperty, (double)100);
    sliderHolder.SetValue(Slider.MinimumProperty, (double)0);
    var dataTemplate = new DataTemplate();
    dataTemplate.VisualTree = sliderHolder;
    dataTemplate.DataType = typeof(DataGridTemplateColumn);
    pcColumn.CellTemplate = dataTemplate;
}
于 2013-03-19T17:18:31.353 回答