wpf 自定义窗体的实现

首先创建自定义窗体的资源文件

<ControlTemplate x:Key="BaseWindowControlTemplate" TargetType="Window">
<Grid>
<Grid.Background>
<ImageBrush ImageSource="Images/MainBackground.png" Stretch="Fill"/>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="9*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" >
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Margin="30,20,0,0" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Source="pack://application:,,,/WpfControlStyles;component/Images/logo.png"/>
<StackPanel Grid.Column="1" Margin="0,0,20,0" Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Right">
<StackPanel.Background>
<ImageBrush ImageSource="pack://application:,,,/WpfControlStyles;component/Images/CloseBackground.png"/>
</StackPanel.Background>
<Button x:Name="BtnMinimized" Style="{StaticResource BtnMinimization}" VerticalAlignment="Center" HorizontalAlignment="Center" Content="最小化"/>
<Button x:Name="BtnClose" Style="{StaticResource BtnCloseBaseWindow}" VerticalAlignment="Center" HorizontalAlignment="Center" Content="关闭"/>
</StackPanel>
</Grid>
<ContentPresenter Grid.Row="1" Margin="30"/>
</Grid>
</ControlTemplate>

<Style x:Key="BaseWindow" TargetType="Window">
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="WindowState" Value="Maximized"/>
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="ResizeMode" Value="NoResize"/>
<Setter Property="Template" Value="{StaticResource BaseWindowControlTemplate}"/>
</Style>

将资源文件的样式加载到窗体中

public class BaseWindow : Window
{
ResourceDictionary res;

public BaseWindow()
{
res = new ResourceDictionary();

//获取资源文件
res.Source = new Uri("WpfControlStyles;component/Generic.xaml", UriKind.Relative);

//获取window窗体的样式
this.Style = res["BaseWindow"] as Style;
this.Loaded += BaseWindow_Loaded;
}

public void BaseWindow_Loaded(object sender, RoutedEventArgs e)
{
ControlTemplate baseWindowTemplate = res["BaseWindowControlTemplate"] as ControlTemplate;
Button button = baseWindowTemplate.FindName("BtnClose", this) as Button;
button.Click += delegate
{
this.Close();
};

Button buttonMin = baseWindowTemplate.FindName("BtnMinimized", this) as Button;
buttonMin.Click += delegate
{
this.WindowState = WindowState.Minimized;
};
}
}

上一篇:css样式书写顺序


下一篇:css的文本属性