[英]Create a grid in WPF with a FrameworkElementFactory
in short in am making out static XAML
description UI into a dynamically created one.简而言之,就是将静态XAML
描述 UI 制作成动态创建的 UI。 Here is the XAML
code that I want to replicate in c#:这是我想在 c# 中复制的XAML
代码:
<GridViewColumn.HeaderTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0"
Margin="4,0,5,0"
VerticalAlignment="Center"
IsChecked="{Binding Path=DataContext.AreAllSelected,
RelativeSource={RelativeSource AncestorType=ListView},
Mode=OneWay}"
Command="{Binding Path=DataContext.ChangeAllSourcesSelection,
RelativeSource={RelativeSource AncestorType=ListView}}" />
<TextBlock Grid.Column="1"
VerticalAlignment="Center"
UI:DisplayedObjectProperties.DisplayedObject="{Binding}" />
</Grid>
</DataTemplate>
</GridViewColumn.HeaderTemplate>
And here is what I have come up with:这是我想出的:
GridViewColumn col = new GridViewColumn();
DataTemplate template = new DataTemplate();
FrameworkElementFactory gridFactory = new FrameworkElementFactory(typeof(Grid));
FrameworkElementFactory col1 = new FrameworkElementFactory(typeof(ColumnDefinition));
FrameworkElementFactory col2 = new FrameworkElementFactory(typeof(ColumnDefinition));
col1.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Auto));
col2.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star));
gridFactory.AppendChild(col1);
gridFactory.AppendChild(col2);
FrameworkElementFactory boxFactory = new FrameworkElementFactory(typeof(CheckBox));
boxFactory.SetValue(Grid.ColumnProperty, 1);
boxFactory.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
FrameworkElementFactory tBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
tBlockFactory.SetValue(Grid.ColumnProperty, 2);
tBlockFactory.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
tBlockFactory.SetValue(TextBlock.TextProperty, LanguageManager.Parse(columnVM.ColumnName));
gridFactory.AppendChild(boxFactory);
gridFactory.AppendChild(tBlockFactory);
template.VisualTree = gridFactory;
col.HeaderTemplate = template;
However this does not give me the desired effect as both the CheckBox and the TextBlock seem to be in the same column.然而,这并没有给我想要的效果,因为 CheckBox 和 TextBlock 似乎在同一列中。 How do I assign each to the respective column?我如何将每个分配给相应的列? As you can see I've done some strange appendings, because I have no Idea what I'm doing.正如你所看到的,我做了一些奇怪的附加,因为我不知道我在做什么。
You should set the Grid.Column
attached property of the TextBlock
to 1:您应该将TextBlock
的Grid.Column
附加属性设置为 1:
tBlockFactory.SetValue(Grid.ColumnProperty, 1);
There is no reason to set the property for boxFactory
since it should have the default value of 0.没有理由为boxFactory
设置属性,因为它应该具有默认值 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.