(文章目录)
前言
MahApps.Metro是一个用于开发Windows应用程序的开源.NET库,它可以提供一种简单的方式来为WPF应用程序添加丰富的用户界面元素。
MahApps.Metro官方文档:https://mahapps.com/docs/
MahApps.Metro源码网址:https://github.com/MahApps/MahApps.Metro
一、MahApps.Metro基于WPF的UI控件库
1.安装包
MahApps.Metro
2.添加资源
在app.xaml中添加资源
<!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<!-- Theme setting -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml" />
3.主视图改造
主视图的cs文件需要继承MetroWindow
public partial class StartView : MetroWindow
{
public StartView()
{
InitializeComponent();
}
}
<mah:MetroWindow x:Class="WpfApp8.StartView"
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:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:cal="http://www.caliburnproject.org"
xmlns:local="clr-namespace:WpfApp8"
mc:Ignorable="d"
GlowBrush="{DynamicResource MahApps.Brushes.Accent}"
ResizeMode="CanResizeWithGrip"
Title="StartView" Height="300" Width="600" WindowStartupLocation="CenterScreen">
<StackPanel>
<TextBox Name="TextContent"/>
<Button x:Name="testBtn" Content="testBtn" Background="LightCyan"/>
<ListBox Name="ListBoxItems" MinHeight="230" Background="LightGray"
cal:Message.Attach="[Event SelectionChanged] = [Action ListBoxItems_SelectionChanged($source,$eventArgs)];
[Event MouseUp]=[ListBoxItems_MouseUp($source,$eventArgs)]" />
</StackPanel>
</mah:MetroWindow>
4.视图的数据源
因为使用的是cm框架,相关数据代码如下:
class StartViewModel : Screen
{
public StartViewModel()
{
ListBoxItems = new ObservableCollection<string>() { };
ListBoxItems.Add("愚公一号");
ListBoxItems.Add("愚公二号");
ListBoxItems.Add("愚公三号");
}
public ObservableCollection<string> ListBoxItems { get; set; }
public string TextContent { get; set; }
public void testBtn()
{
TextContent = "hello world!";
NotifyOfPropertyChange(()=> TextContent);
}
public void ListBoxItems_MouseUp(object sender, MouseButtonEventArgs e)
{
ListBox listbox = sender as ListBox;
MessageBox.Show("当前操作的控件名称是:"+ listbox.Name);
}
public void ListBoxItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TextContent = (sender as ListBox).SelectedItem.ToString();
NotifyOfPropertyChange("TextContent");
}
}
5.运行程序
可以看到三个主题控件都显示出来了