如何用代码制作数据网格模板
本文关键字:数据网 网格 数据 何用 代码 | 更新日期: 2023-09-27 18:04:47
我想让这个XAML模板只使用c#:
<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#来制作整个模板。
我不知道从哪里开始。
我认为你所需要的就是在这个网站上查看它:
http://harishasanblog.blogspot.ca/2011/01/create-datagrid-in-wpf-using-code.html您应该使用FrameworkElementFactory
(msdn)
<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;
}