WPF引入MaterialDesign -- 好看的控件先从button开始

1,219 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情

前言

没有前言

在WPF控件效果这一块,很显然比winfrom要好很多,但想要做出真正好看的控件,我个人觉得还是需要用一些已有的东西比较好,比如MaterialDesign,控件种类多,自带很多图标,上手比较容易,还囊括了多个平台,所以MaterialDesign算是一个比较好的选择。

正文

一、下载MaterialDesign

GitHub地址:github.com/MaterialDes…

进去找一个你想要的版本,然后下载DemoApp.zip:

image-20221004131800697

下载到本地进行解压,里面有几个不同环境下的编译成功的文件夹,根据你的编译环境选择一个打开它,然后找到里面的exe文件,最好是给它在桌面上建立一个快捷方式,在需要用的时候开它来看看里面提供的样式的代码,注意,不能直接复制这个exe文件到桌面,因为文件夹里面的东西都是它的依赖,所以建议使用快捷方式。

image-20221004132056788

打开之后是这样的

image-20221004121204177

二、下载NuGet包

现在打开我们自己的项目

  1. 在NuGet管理中,搜索MaterialDesignThemes,安装第一个即可。
image-20221004132553442
  1. 搜索MaterialDesignColors,安装第一个
image-20221004133019046

三、引用MaterialDesign

可参考:官方文档(英文版的),或者Wiki,内有如何在XAML中引用MaterialDesign的方法

image-20221004121450825

也可以参考我下面的内容:

  1. 编辑App.xaml,主要是要把<Application.Resources>中间那一块复制进去,前后的内容按照你原来的样子就可以了
<?xml version="1.0" encoding="UTF-8"?>
<Application . . .>
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>
image-20221004133523067
  1. 在窗体的XAML文件(如MainWindow.xaml)中进行引用
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
image-20221004133440490

四、开始使用MaterialDesign

MaterialDesign中提供了很多控件样式,还记得刚刚在GitHub下载打开的那个exe文件吗?到那里去找到自己想要的控件的样子,然后将代码复制到自己的XAML文件中即可。

比如我想使用下图这个button

image-20221004133224472

我先点击COPY把代码复制下来,然后放到我的XAML文件中,如下:

<Window x:Class="TestWPF.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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:local="clr-namespace:TestWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="400">
	<Grid>
		<Button
    Style="{StaticResource MaterialDesignRaisedLightButton}"
    Width="100"
    ToolTip="Resource name: MaterialDesignRaisedLightButton">
			_LIGHT
		</Button>
	</Grid>
</Window>

效果:

QQ22918914922917714320221004134245

其他控件的使用方法也差不多都是这样,根据自己的喜好去选择就好啦。

后记

本文简单的介绍了MaterialDesign的使用方法,具体的还需要大家自己在实战中进行学习,同时多看官方文档,或者多去百度。

希望对你有帮助🥰。