Wpf 如何以编程方式解释样式
在我的应用程序中,我必须在代码隐藏中操作DataGrid(DataGrid也是在运行时的代码隐藏中创建的),我想为DataGrid设置以下样式Wpf 如何以编程方式解释样式,wpf,wpfdatagrid,code-behind,Wpf,Wpfdatagrid,Code Behind,在我的应用程序中,我必须在代码隐藏中操作DataGrid(DataGrid也是在运行时的代码隐藏中创建的),我想为DataGrid设置以下样式 <DataGrid.RowHeaderStyle> <Style TargetType="DataGridRowHeader"> <Setter Property="Visibility" Value="Collapsed"/> <Setter Property="Temp
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="Visibility" Value="Collapsed"/>
<Setter Property="Template" Value="{x:Null}"/>
</Style>
</DataGrid.RowHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridRow">
<Border BorderThickness="{TemplateBinding Border.BorderThickness}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" Name="DGR_Border" SnapsToDevicePixels="True">
<SelectiveScrollingGrid> <!--How to translate this-->
<DataGridCellsPresenter ItemsPanel="{TemplateBinding ItemsControl.ItemsPanel}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
</SelectiveScrollingGrid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
只需创建另一个
FrameworkElementFactory
,其类型为System.Windows.Controls.Primitives.SelectiveScrollingGrid
:
...
var selectiveScrollingGridFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Primitives.SelectiveScrollingGrid));
elemFactory.AppendChild(selectiveScrollingGridFactory);
var cellsPresenterFactory = new FrameworkElementFactory(typeof(DataGridCellsPresenter));
cellsPresenterFactory.SetValue(DataGridCellsPresenter.ItemsPanelProperty, new TemplateBindingExtension(ItemsControl.ItemsPanelProperty));
cellsPresenterFactory.SetValue(DataGridCellsPresenter.SnapsToDevicePixelsProperty, new TemplateBindingExtension(UIElement.SnapsToDevicePixelsProperty));
selectiveScrollingGridFactory.AppendChild(selectiveScrollingGridFactory);
...
请注意,以编程方式创建模板的推荐方法是使用
XamlReader
类的load
方法从string
或内存流加载XAML,如MSDN上的文档所述:谢谢您的评论,现在,我在XAML中定义了样式,然后将其加载到代码隐藏中,它非常适合我!
...
var selectiveScrollingGridFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Primitives.SelectiveScrollingGrid));
elemFactory.AppendChild(selectiveScrollingGridFactory);
var cellsPresenterFactory = new FrameworkElementFactory(typeof(DataGridCellsPresenter));
cellsPresenterFactory.SetValue(DataGridCellsPresenter.ItemsPanelProperty, new TemplateBindingExtension(ItemsControl.ItemsPanelProperty));
cellsPresenterFactory.SetValue(DataGridCellsPresenter.SnapsToDevicePixelsProperty, new TemplateBindingExtension(UIElement.SnapsToDevicePixelsProperty));
selectiveScrollingGridFactory.AppendChild(selectiveScrollingGridFactory);
...