我想只使用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#制作整个模板 我不知道从哪里开始。
答案 0 :(得分:2)
我认为你需要的只是在这个网站上查看它:
http://harishasanblog.blogspot.ca/2011/01/create-datagrid-in-wpf-using-code.html
答案 1 :(得分: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;
}