如何以编程方式分配样式

Doo*_*ght 1 c# wpf xaml styles

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

所以我希望我必须动态设置样式?因为 xaml 中不存在该框架。

我不明白的是如何分配自定义模板。或者更好的是,以全局方式处理适合特定类别的任何框架。标记或键入等。

下面是我尝试测试的模板。但这不起作用。假设代码丢失,因此开始检查代码隐藏样式设置,但到目前为止还没有运气。

应用程序.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>
Run Code Online (Sandbox Code Playgroud)

MyWindow.xaml.cs

 Frame newFrame = new Frame();
 newFrame.Content = content;

 newFrame.Template = ControlTemplate ...?
Run Code Online (Sandbox Code Playgroud)

Eli*_*gan 5

选项1:

  1. 为您的类型创建没有键(隐式)的样式
  2. 在样式中添加 ControlTemplate
  3. 当您添加控件(即使是从代码中添加)时,它将获得您刚刚创建的默认样式

代码 Ex 带有一个按钮,可以从包含的窗口获取历史样式:

<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>
Run Code Online (Sandbox Code Playgroud)

从后面的代码创建按钮:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var button = new Button();
        this.Content = button;
    }
}
Run Code Online (Sandbox Code Playgroud)

选项2:

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

代码示例:

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

Frame newFrame = new Frame();

newFrame.Style = yourStyle;
Run Code Online (Sandbox Code Playgroud)