简而言之,我正在把静态XAML描述UI变成一个动态创建的UI。下面是我想在XAML中复制的c#代码:
<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>以下是我想出的:
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;然而,这并没有给我想要的效果,因为CheckBox和TextBlock似乎都在同一列中。如何将每个列分配给各自的列?如你所见,我做了一些奇怪的附录,因为我不知道自己在做什么。
发布于 2017-07-11 14:01:47
应该将Grid.Column附加的TextBlock属性设置为1:
tBlockFactory.SetValue(Grid.ColumnProperty, 1);没有理由为boxFactory设置属性,因为它的默认值应为0。
https://stackoverflow.com/questions/45036667
复制相似问题