如何以编程方式分配样式

本文关键字:分配 样式 方式 编程 | 更新日期: 2023-09-27 18:16:52

我正在尝试将我的xaml样式之一设置到我的页面框架中。它是在代码中创建的,并动态地分配给布局。

所以我希望我必须动态地设置样式?由于xaml.

中不存在框架。

我不明白的是如何分配自定义模板。或者更好的是,以一种全局的方式适用于任何符合特定类别的框架。标签,或类型等

下面是我的模板,我试图测试。但这行不通。假设代码丢失了,所以开始检查代码隐藏样式设置,但到目前为止还没有运气。

App.xaml

<!-- http://paulstovell.com/blog/wpf-navigation -->
<ControlTemplate TargetType="Frame" x:Key="frame" >
    <DockPanel Margin="7">
        <StackPanel 
            Margin="7"
            Orientation="Horizontal"
            DockPanel.Dock="Top"
            >
                <Button 
                Content="Avast! Go back!" 
                Command="{x:Static NavigationCommands.BrowseBack}" 
                IsEnabled="{TemplateBinding CanGoBack}" 
                />
                <Button 
                Content="Forward you dogs!" 
                Command="{x:Static NavigationCommands.BrowseForward}" 
                IsEnabled="{TemplateBinding CanGoForward}" 
                />
            </StackPanel>
            <Border 
            BorderBrush="Green"
            Margin="7"
            BorderThickness="7"
            Padding="7"
            CornerRadius="7"
            Background="White"
            >
            <ContentPresenter />
        </Border>
    </DockPanel>
</ControlTemplate>

MyWindow.xaml.cs

 Frame newFrame = new Frame();
 newFrame.Content = content;
 newFrame.Template = ControlTemplate ...?

如何以编程方式分配样式

选项1:

  1. 为类型
  2. 创建一个没有Key(隐式)的样式在样式中添加ControlTemplate
  3. 当你添加控件(甚至从代码),它会得到你刚刚创建的默认样式

Code Ex带有一个按钮,该按钮从包含的窗口获得hist样式:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="Template">
               <ControlTemplate>
                   <... Your Template ...>
               </ControlTemplate>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
    </Grid>
</Window>

从后面的代码创建按钮:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var button = new Button();
        this.Content = button;
    }
}

选项2:

  1. 用键创建样式。
  2. 在样式中添加ControlTemplate
  3. 将样式添加到App资源中
  4. 从应用程序资源中获取样式并设置样式(和模板):

代码前:

var yourStyle = (Style)Application.Current.Resources["Resource_Name"]);
Frame newFrame = new Frame();
newFrame.Style = yourStyle;