自定义WPF窗口样式

时间:2016-10-05 19:37:46

标签: wpf xaml window contentpresenter

我正在尝试制作自定义窗口样式。目标是创建一个模板,该模板可以由我的应用程序中的每个窗口使用。模板包含工具栏,标题和“窗口将使用的区域”。问题是:当我使用我的风格时,我再也无法添加网格和控制。

的App.xaml

<Style x:Key="CustomWindowStyle" TargetType="{x:Type Window}">
  <Setter Property="WindowStyle" Value="None"/>
  <Setter Property="AllowsTransparency" Value="True"/>
  <Setter Property="ResizeMode" Value="NoResize"/>
  <Setter Property="Background" Value="MintCream"/>
  <Setter Property="BorderBrush" Value="#0046E7"/>
  <Setter Property="BorderThickness" Value="2"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Window}">
        <Grid Background="{TemplateBinding Background}">
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
          </Grid.RowDefinitions>
          <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto"/>
          </Grid.ColumnDefinitions>
          <StackPanel Grid.ColumnSpan="2">
            <TextBlock TextAlignment="Center"
                       Margin="0 10 0 0"
                       FontSize="22"
                       FontWeight="DemiBold"
                       Foreground="RoyalBlue"
                       Text="{TemplateBinding Title}"/>
          </StackPanel>
          <StackPanel Grid.Row="0" Grid.Column="1"
                      Orientation="Horizontal"
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Center"
                      Margin="0 10 15 0">
            <Button Style="{StaticResource MinimizeButtonStyle}"
                    Width="25"
                    Height="22"
                    Margin="0 0 10 0"/>
            <Button Style="{StaticResource CloseButtonStyle}"
                    Width="25"
                    Height="22"/>
          </StackPanel>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

MainWindow.xaml

<Window x:Class="WindowForHW2.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:WindowForHW2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525"
    Style="{StaticResource CustomWindowStyle}">
<Grid>
  <Button Width="100" Height="40" Content="Hello"/>
</Grid>

模板工作,但我不能再添加smth: Window:

1 个答案:

答案 0 :(得分:4)

您需要在ContentPresenter的{​​{1}}内添加Content。试试这个。

Window