在代码[WPF]中设置ControlTemplate
如何使用ControlTemplate中的一些UI元素设置网格对象?我尝试使用这段代码,但我不明白如何将Grid对象设置为FrameworkElementFactory对象。谢谢在代码[WPF]中设置ControlTemplate,wpf,controltemplate,frameworkelementfactory,Wpf,Controltemplate,Frameworkelementfactory,如何使用ControlTemplate中的一些UI元素设置网格对象?我尝试使用这段代码,但我不明白如何将Grid对象设置为FrameworkElementFactory对象。谢谢 ControlTemplate CellControlTemplate = new ControlTemplate(); // my control template Grid CellGrid = new Grid(); // my grid (I want add it to my control
ControlTemplate CellControlTemplate = new ControlTemplate(); // my control template
Grid CellGrid = new Grid(); // my grid (I want add it to my control template
FrameworkElementFactory root = new FrameworkElementFactory(typeof(Grid));
// ???
CellControlTemplate.VisualTree = root;
我需要它来替换代码隐藏中的xaml设计风格:
<Style TargetType="{x:Type igDP:CellValuePresenter}" x:Key="PStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}">
<Grid Margin="4">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.RowSpan="2" Grid.Column="0"
FontWeight="DemiBold"
FontSize="18"
VerticalAlignment="Center"
Text="{Binding Path=DataItem.DINAMIC_COLUMN}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我必须这样做,因为我想在运行时从代码更改textbox的绑定路径。你知道其他的方法吗?谢谢。以下是解决方案:
var grid = new FrameworkElementFactory(typeof(Grid));
// assign template to grid
CellControlTemplate.VisualTree = grid;
// define grid's rows
var r = new FrameworkElementFactory(typeof(RowDefinition));
grid.AppendChild(r);
// define grid's columns
var c = new FrameworkElementFactory(typeof(ColumnDefinition));
grid.AppendChild(c);
//... etc
谢谢大家。以下是解决方案:
var grid = new FrameworkElementFactory(typeof(Grid));
// assign template to grid
CellControlTemplate.VisualTree = grid;
// define grid's rows
var r = new FrameworkElementFactory(typeof(RowDefinition));
grid.AppendChild(r);
// define grid's columns
var c = new FrameworkElementFactory(typeof(ColumnDefinition));
grid.AppendChild(c);
//... etc
谢谢大家。你到底想用这个达到什么目的?此外,网格不是控件,它们只是存储控件,我认为您可能希望将DataTemplate应用于listbox,而不是使用样式。此样式包含控件模板。我有一些控件,我想将其添加到此控件模板中。我将这些控件放在网格中,并尝试将此网格设置为我的控件模板。您到底想用它实现什么?此外,网格不是控件,它们只是存储控件,我认为您可能希望将DataTemplate应用于listbox,而不是使用样式。此样式包含控件模板。我有一些控件,我想将其添加到此控件模板中。我将这些控件放在网格中,并尝试将此网格设置为我的控件模板。