首页 » 技术分享 » MahApps.Metro使用

MahApps.Metro使用

 

MahApps.Metro使用

下载MahApps.Metro

PM> Install-Package MahApps.Metro

MainWindow.xaml中添加

xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"

然后将Window标签替换为如下标签

<Controls:MetroWindow x:Class="WpfApplication.MainWindow"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
                  Title="MainWindow"
                  Height="600"
                  Width="800">

</Controls:MetroWindow>

MainWindow.xaml.cs添加

using MahApps.Metro.Controls;

namespace WpfApplication
{
  public partial class MainWindow : MetroWindow
  {
    public MainWindow()
    {
      InitializeComponent();
    }
  }
}

使用内置的样式App.xaml

<Application x:Class="WpfApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <!-- 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" />
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
        <!-- Accent and AppTheme setting -->
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>

显示标题栏、图标、最大化最小化按钮的显示

<Controls:MetroWindow x:Class="WpfApplication.MainWindow"
                      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
                      Title="MainWindow"
                      Height="600"
                      Width="800"
                      Icon="mahapps.metro.logo2.ico"
                      ShowIconOnTitleBar="True"
                      ShowTitleBar="True">

    </Controls:MetroWindow>

WindowButtonCommands are the minimize, maximize/restore, and close buttons. You can hide the buttons with ShowMinButton="True|False"ShowMaxRestoreButton="True|False" and ShowCloseButton="True|False".

The visibility of the minimize and maximize/restore buttons are also effected by the ResizeMode. If ResizeMode="NoResize" the buttons are collapsed. If ResizeMode="CanMinimize" the maximize/restore button is collapsed.

记住窗口位置

aveWindowPosition=”True|False”(默认False选项)。将此属性设置为True将意味着在下一次发射,将被自动定位和尺寸对它的出口。这种设计为提高ux和速度发展为一个“管道”,UI是定期进行的。

修改标题栏

可以添加自己的控制 LeftWindowsCommands 或 RightWindowsCommands

<MetroWindow> ... </MetroWindow>

MainWindow.xaml.cs内添加:

<Controls:MetroWindow.RightWindowCommands>
  <Controls:WindowCommands>
    <Button Content="settings" />
    <Button>
      <StackPanel Orientation="Horizontal">
        <Rectangle Width="20"
                   Height="20"
                   Fill="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}">
          <Rectangle.OpacityMask>
            <VisualBrush Stretch="Fill" Visual="{StaticResource appbar_cupcake}" />
          </Rectangle.OpacityMask>
        </Rectangle>
        <TextBlock Margin="4 0 0 0"
                   VerticalAlignment="Center"
                   Text="deploy cupcakes" />
      </StackPanel>
    </Button>
  </Controls:WindowCommands>
</Controls:MetroWindow.RightWindowCommands>

显示图标需要加载MahApps.Metro.Resources资源

MahApps.Metro.Resources使用

下载MahApps.Metro.Resources

PM> Install-Package MahApps.Metro.Resources

MainWindow.xaml文件中添加

<Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Resources/Icons.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

使用

<Rectangle>
        <Rectangle.Fill>
            <VisualBrush Visual="{StaticResource appbar_add}" />
        </Rectangle.Fill>
    </Rectangle>

或者

<Rectangle Fill="Black">
    <Rectangle.OpacityMask>
        <VisualBrush Visual="{StaticResource appbar_add}" Stretch="Fill" />
    </Rectangle.OpacityMask>
</Rectangle>

如何改变目前的主题 Styles

You can choose between these available accents:

“Red”, “Green”, “Blue”, “Purple”, “Orange”, “Lime”, “Emerald”, “Teal”, “Cyan”, “Cobalt”, “Indigo”, “Violet”, “Pink”, “Magenta”, “Crimson”, “Amber”, “Yellow”, “Brown”, “Olive”, “Steel”, “Mauve”, “Taupe”, “Sienna”

and these themes:

“BaseLight”, “BaseDark”

通过App.xaml,直接修改其中对应的部分

<Application x:Class="MahAppsMetroThemesSample.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />

                <!-- accent resource -->
                <!-- change "Cobalt" to the accent color you want -->

                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Cobalt.xaml" />

                <!-- theme resource -->
                <!-- change "BaseLight" to the theme you want -->
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

通过ThemeManager

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        // get the current app style (theme and accent) from the application
        // you can then use the current theme and custom accent instead set a new theme
        Tuple<AppTheme, Accent> appStyle = ThemeManager.DetectAppStyle(Application.Current);

        // now set the Green accent and dark theme
        ThemeManager.ChangeAppStyle(Application.Current,
                                    ThemeManager.GetAccent("Green"),
                                    ThemeManager.GetAppTheme("BaseDark")); // or appStyle.Item1

        base.OnStartup(e);
    }
}

在主窗口中修改

MainWindow.xaml文件

<Controls:MetroWindow.Resources>
    <ResourceDictionary>
       <ResourceDictionary.MergedDictionaries>
            <!-- this window should be blue -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <!-- and should use the light theme -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Controls:MetroWindow.Resources>

主类MetroWindow中

public partial class AccentStyleWindow : MetroWindow
{
    public void ChangeAppStyle()
    {
        // set the Red accent and dark theme only to the current window
        ThemeManager.ChangeAppStyle(this,
                                    ThemeManager.GetAccent("Red"),
                                    ThemeManager.GetAppTheme("BaseDark"));
    }
}

还可以自定义主题

Controls控件

MetroWindow

窗口有边框:

<Controls:MetroWindow x:Class="MahApps.Metro.Simple.Demo.MainWindow"
                      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
                      Title="MainWindow"
                      Height="200"
                      Width="600"

                      BorderBrush="{DynamicResource AccentColorBrush}"
                      BorderThickness="1"

                      WindowStartupLocation="CenterScreen">

</Controls:MetroWindow>

发光的边框:

<Controls:MetroWindow x:Class="MahApps.Metro.Simple.Demo.MainWindow"
                      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
                      Title="MainWindow"
                      Height="200"
                      Width="600"

                      GlowBrush="{DynamicResource AccentColorBrush}"

                      WindowStartupLocation="CenterScreen">

</Controls:MetroWindow>

有阴影的边框:

<Controls:MetroWindow x:Class="MahApps.Metro.Simple.Demo.MainWindow"
                      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
                      Title="MainWindow"
                      Height="200"
                      Width="600"

                      BorderThickness="0" 
                      GlowBrush="Black"
                      ResizeMode="CanResizeWithGrip"

                      WindowTransitionsEnabled="False"
                      WindowStartupLocation="CenterScreen">

</Controls:MetroWindow>

Buttons

DEFAULT LOOK

METROCIRCLEBUTTON

<Button Style="{DynamicResource MetroCircleButtonStyle}" Content="Button"/>

SQUAREBUTTON

<Button Style="{DynamicResource SquareButtonStyle}" Content="Button"/>

ACCENTEDSQUAREBUTTON

<Button Style="{StaticResource AccentedSquareButtonStyle}" Content="Button"/>

FLATBUTTON

<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatButton.xaml" />

ContextMenu

您可以使用您熟悉的快捷菜单

<ContextMenu>
  <MenuItem Command="ApplicationCommands.New" />
  <MenuItem Command="ApplicationCommands.Delete" />
  <MenuItem Command="ApplicationCommands.Print" />
</ContextMenu>

如果你想使用快捷菜单的一部分被声明为资源和共享使用 CompositeCollection

<CompositeCollection x:Key="ContextMenuBase"
 x:Shared="False">
  <MenuItem Command="ApplicationCommands.New" />
  <MenuItem Command="ApplicationCommands.Delete" />
  <Separator />
  <StaticResource ResourceKey="ContextMenuItemRefresh" />
  <Separator />
</CompositeCollection>


<ContextMenu>
  <ContextMenu.ItemsSource>
<CompositeCollection>
  <CollectionContainer Collection="{StaticResource ContextMenuBase}"></CollectionContainer>
  <MenuItem Command="ApplicationCommands.Print" />
</CompositeCollection>
  </ContextMenu.ItemsSource>
</ContextMenu>

当你运行应用程序的绑定错误:

System.Windows.Data Error: 4 : Cannot find source for binding with reference ‘RelativeSource FindAncestor, AncestorType=’System.Windows.Controls.ItemsControl’, AncestorLevel=’1’’. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is ‘MenuItem’ (Name=’’); target property is ‘VerticalContentAlignment’ (type ‘VerticalAlignment’)

这是一个已知的问题在WPF和解决方法是创建一个自定义 MenuItem 风格:

<Style TargetType="{x:Type MenuItem}"
   BasedOn="{StaticResource MetroMenuItem}">
  <Setter Property="HorizontalContentAlignment"
  Value="Left" />
  <Setter Property="VerticalContentAlignment"
  Value="Center" />
  </Style>

Data Grid

In order for the style to be applied, you will have to include references to the Styles/Controls resource dictionary in your App.xaml and the namespace xmlns:controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro" in the window you are using.

Alternative Style

MahApps.Metro also provides an alternative style, AzureDataGrid that attempts to mimic the DataGrid found on Microsoft Azure. To use it instead of the default style, simple set the DataGrid’s Style property to {StaticResource AzureDataGrid. As usual, make sure that you have your references defined.

<DataGrid ItemsSource="{Binding People}" Margin="10,20,10,0"
  AutoGenerateColumns="True"
  Style="{StaticResource AzureDataGrid}">

</DataGrid> 

DataGrid Numeric Updown Control

In addition to styling the DataGrid, MahApps.Metro also provides a control that allows users to add a NumericUpDown as one of their DataGrid’s columns. To add the custom column to your DataGrid, add DataGridNumericUpDownColumn under the MahApps namespace to your DataGrid.Columns properties. Be sure to set AutoGenerateColumns to False if you have not already done so.

<DataGrid ItemsSource="{Binding Path=Albums}"
  Grid.Row="0"
  AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Genre"
Binding="{Binding Genre.Name}" />
<controls:DataGridNumericUpDownColumn Header="Price"
  Binding="{Binding Price}"
  StringFormat="C"
  Minimum="0" />
</DataGrid.Columns>
</DataGrid>

DataGrid Checkbox

Lastly, MahApps.Metro provides an ElementStyle for the DataGridCheckBoxColumn. In order to apply the style, you will have to set the ElementStyle property of the DataGridCheckBoxColumn to {DynamicResource MetroDataGridCheckBox} as shown in the code sample below.

<DataGrid ItemsSource="{Binding Path=Albums}"
  Grid.Row="0"
  AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn ElementStyle="{DynamicResource MetroDataGridCheckBox}"
EditingElementStyle="{DynamicResource MetroDataGridCheckBox}"
Header="IsSelected"
Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=IsSelected, Mode=OneWay}"
/>
</DataGrid.Columns>
</DataGrid>

Dialogs

Message dialog

对话框还可以显示简单消息的ShowMessageAsync方法。扩展方法MetroWindow因此,呼叫从它的窗口类。

await this.ShowMessageAsync("This is the title", "Some message");

有可选的额外参数的简单的按钮,例如 Ok Cancel 并设置主题颜色和动画选项。

Progress dialog

var controller = await this.ShowProgressAsync("Please wait...", "Progress message");

This method returns a ProgressDialogController object that exposes the SetProgress method, use it to set the current progress.

FlipView

<Controls:FlipView Height="200" 
   IsBannerEnabled="True" 
   SelectionChanged="FlipView_SelectionChanged"
   Margin="0, 0, 10, 0">
<Controls:FlipView.Items>
<Grid Background="#2E8DEF">
<Rectangle Margin="0, 0, 10, 0" Width="50" Height="50">
<Rectangle.Fill>
<VisualBrush Visual="{StaticResource appbar_cupcake}" />
</Rectangle.Fill>
</Rectangle>
</Grid>
<Grid Background="#00A600">
<Rectangle Margin="0, 0, 10, 0" Width="50" Height="50">
<Rectangle.Fill>
<VisualBrush Visual="{StaticResource appbar_xbox}" />
</Rectangle.Fill>
</Rectangle>
</Grid>
<Grid Background="#BF1E4B">
<Rectangle Margin="0, 0, 10, 0" Width="50" Height="50">
<Rectangle.Fill>
<VisualBrush Visual="{StaticResource appbar_chess_horse}" />
</Rectangle.Fill>
</Rectangle>
</Grid>
</Controls:FlipView.Items>
</Controls:FlipView>

The Banner

private void FlipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var flipview = ((FlipView)sender);
switch (flipview.SelectedIndex)
{
case 0:
flipview.BannerText = "Cupcakes!";
break;
case 1:
flipview.BannerText = "Xbox!";
break;
case 2:
flipview.BannerText = "Chess!";
break;
}
}

The Control Buttons

The control buttons (the next and previous buttons) allow the user to flip through the items using their mouse. The buttons can be disabled by calling HideControlButtons and renabled by calling ShowControlButtons.

The user can also flip through the items using the arrows on their keyboard.

Automated scrolling (batteries not included)

Disabling the control buttons is useful when you want to provide an automated scrolling experience. This can be implemented by using a timer and by incrementing SelectedIndex by 1 until the index is equal to Items.Length - 1. At that point, you would reset SelectedIndex to 0.

Flyouts

Add the following code to your MetroWindow:

<Controls:MetroWindow.Flyouts>
<Controls:FlyoutsControl>

</Controls:FlyoutsControl>
</Controls:MetroWindow.Flyouts>

This is the container for the flyouts. Inside this container add the following:

<Controls:Flyout Header="Flyout" Position="Right" Width="200">
<!-- Your custom content here -->
</Controls:Flyout>

Themed flyouts

As of version 0.12, flyouts can have various themes, assignable through the Theme property, those are:

Adapt,
Inverse,
Dark,
Light,
Accent
  • Adapt adapts the flyout theme to the host window’s theme.
  • Inverse has the inverse theme of the host window’s theme.
  • Dark will always be the dark theme, this is also the default value.
  • Light will always be the light theme.
  • Accent adapts the flyout theme to the host window’s theme, it looks like this for the blue theme

WindowCommandsOverlayBehaviorn

MetroWindow has overlay properties for LeftWindowCommands, RightWindowCommands, WindowButtonCommands and the Icon to handle the topmost status, even if a flyout is shown.

public WindowCommandsOverlayBehavior LeftWindowCommandsOverlayBehavior
public WindowCommandsOverlayBehavior RightWindowCommandsOverlayBehavior
public WindowCommandsOverlayBehavior WindowButtonCommandsOverlayBehavior
public WindowCommandsOverlayBehavior IconOverlayBehavior

These are the values for WindowCommandsOverlayBehavior

Never // Doesn't overlay flyouts nor a hidden TitleBar.
Flyouts // Overlays opened Flyout controls.
HiddenTitleBar // // Overlays a hidden TitleBar.
Always

WindowCommandsOverlayBehavior.Always

WindowCommandsOverlayBehavior.Never

NumericUpDown

NumericUpDown控件将用来增大或减小数值。

ProgressBar

MetroProgressBar

MetroProgressBar is an alternative and simpler style. Instead of creating a normal ProgressBar use:

<Controls:MetroProgressBar />

Its indeterminate state looks like a ProgressRing but not circular.

ProgressRing

The Progress Ring control is styled after a similar control in Windows 8 to indicate activity rather than a percentage of progress completed.

<Controls:ProgressRing IsActive="True" />

IsActive can easily be bound to a viewmodel property.

<Controls:ProgressRing IsActive="{Binding IsActive}" />

Override Foreground if you wish to change the colour.

<Controls:ProgressRing Foreground="{DynamicResource AccentColorBrush}"/>

RangeSlider

Small Example

<Сontrols:RangeSlider Style="{StaticResource RangeSliderCameraCommonStyle}" 
Minimum="{Binding Path=MinValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Maximum="{Binding Path=MaxValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
LowerValue="{Binding Path=CurrentMinValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
UpperValue="{Binding Path=CurrentMaxValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
LowerValueChanged="OnLowerValueChanged" UpperValueChanged="OnUpperValueChanged"
LowerThumbDragStarted="OnLowerDragStarted"
LowerThumbDragCompleted="OnLowerDragCompleted"
UpperThumbDragStarted="OnUpperDragStarted" 
UpperThumbDragCompleted="OnUpperDragCompleted" 
AutoToolTipPlacement="TopLeft" AutoToolTipPrecision="2" MoveWholeRange="True"
IsSnapToTickEnabled="True" IsMoveToPointEnabled="True" ExtendedMode="True"></Сontrols:RangeSlider>

Slider

If you want to base your custom style on that style, you need to add BasedOn="{StaticResource MetroSlider}"

FlatSlider style

To use that style you need to load resource dictionary <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatSlider.xaml" /> and explicitly set the style of the Slider to Style="{DynamicResource FlatSlider}"

This style could be dynamically changed to:

SplitButton and DropDownButton

SelectedItem and SelectedIndex

This properties usage is just like in Listbox or ComboBox. When one of this properties changed, Content of the button will also changed.

Binding to ObservableCollection or Dictionary

To correctly bind an ObservableCollection or a Dictionary to SplitButton, you need to use ItemsSource and DisplayMemberPath For ex, ItemsSource="{Binding Albums}" DisplayMemberPath="Title"In case you bind simple types like an enum or integer, you dont need to use DisplayMemberPath property, only ItemsSource`.

Orientation

SplitButton supports orientation changing as you can see on the screenshot.

Button commands

You can use button commands for SplitButton

Icon property

You can add separate icon to SplitButton to display it independently from its content. It could be bitmap image or vector icon. Icon="{DynamicResource appbar_alert}"

Example

<Controls:SplitButton 
Icon="{DynamicResource appbar_alert}"
HorizontalContentAlignment="Left"
HorizontalAlignment="Center"
VerticalContentAlignment="Center"
Width="120"
SelectedIndex="2"
ItemsSource="{Binding Albums}"
DisplayMemberPath="Title"
VerticalAlignment="Center" />

Example

Controls:DropDownButton 
VerticalContentAlignment="Center"
Width="120"
Content="Test"
DisplayMemberPath="Title"
Icon="{DynamicResource appbar_music}"
ItemsSource="{Binding Albums}">
</Controls:DropDownButton>

TabControl

There are three included tab styles - AnimatedTabControlSingleRowAnimatedTabControl and the default TabControl. The default TabControl style is included in Controls.xaml, but the other two require specific referencing (make sure to do this after a reference to Controls.xaml)

Default look

This shows the three states - selected/active tab, hover and inactive.

AnimatedTabControl

<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.AnimatedTabControl.xaml" />

Functioning just like the regular TabControl, except it animates every tab change by wrapping everything in a MetroContentControl.

AnimatedSingleRowTabControl

<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.AnimatedSingleRowTabControl.xaml" />

AnimatedSingleRowTabControl functions exactly the same as the AnimatedTabControl except the tabs will only appear on a single line rather than wrapping. Instead of wrapping, arrows (left/right) are presented.

TextBox - MahApps.Metro

Watermark

<TextBox Controls:TextBoxHelper.Watermark="This is a textbox" />

Clear button

Like the watermark, a simple attached property adds in the functionality

<TextBox Controls:TextBoxHelper.ClearTextButton="True" />

Tile

<controls:Tile Title="Hello!" 
TiltFactor="2"
Width="100" Height="100" 
Count="1">
</controls:Tile>

ToggleButton

The default style, available just by placing a ToggleButton control in XAML looks like the default MahApps.Metro button.

<Grid>
<ToggleButton/>
</Grid>

Another style, MetroCircleToggleButtonStyle is available by setting the ToggleButton’s style to MetroCircleToggleButtonStyle. This style changes the button’s background to AccentColorBrush when it is checked. To modify this behaviour, you will have to edit a copy of the control template using Blend.

<ToggleButton Width="50"
              Height="50"
              Margin="0, 10, 0, 0"
              Style="{DynamicResource MetroCircleToggleButtonStyle}">
</ToggleButton>

Using Glyphs Within a Circle Toggle Button

In order to use glyphs, you will have to add a reference to Icons.xaml.

`<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro.Resources;component/Icons.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>`
  1. Nest a Rectangle within the ToggleButton
  2. Set it’s fill to the color you want the icon to have
  3. Set Rectangle.OpacityMask to contain a VisualBrush with a Visual using the icon’s value as a reference.

For example:

<ToggleButton Width="50"
              Height="50"
              Margin="0, 10, 0, 0"
              Style="{DynamicResource MetroCircleToggleButtonStyle}">
    <Rectangle Width="20"
               Height="20"
               Fill="{DynamicResource BlackBrush}">
        <Rectangle.OpacityMask>
            <VisualBrush Stretch="Fill"
                         Visual="{DynamicResource appbar_city}"/>
        </Rectangle.OpacityMask>
    </Rectangle>
</ToggleButton>

Syncing Checked State of ToggleButton with Foreground

By default, any icon you set will retain the same color you set it to even if the ToggleButton is checked. To alter this, you can bind your content’s color to the ToggleButton’s Foreground property which changes to white by default when it is checked.

An example of how to do the binding can be found below:

<ToggleButton Width="50"
              Height="50"
              Margin="0, 10, 0, 0"
              Style="{DynamicResource MetroCircleToggleButtonStyle}">
    <Rectangle Width="20"
               Height="20"
               Fill="{Binding Path=Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ToggleButton}}}">
        <Rectangle.OpacityMask>
            <VisualBrush Stretch="Fill"
                         Visual="{DynamicResource appbar_city}"/>
        </Rectangle.OpacityMask>
    </Rectangle>
</ToggleButton>

ToggleSwitch

The function is very similar to that of a checkbox, but easier to differentiate and easier to use with touch interfaces. Basically though, it can be thought of as a pretty CheckBox:

<Controls:ToggleSwitch Header="WiFi rest state" />

You can bind to/set IsChecked to switch between the two states. You can change the on and off labels by setting

<Controls:ToggleSwitch OnLabel="Yes" OffLabel="No" />

TransitioningContentControl

Taken from Silverlight (specifically this port), TransitioningContentControl is great for switching content smoothly around. At it’s core, TransitioningContentControl is a ContentControl, so only one child element can be displayed at a time. When you change the content, an animation is played switching the two.

<Controls:TransitioningContentControl x:Name="transitioning" Width="150" Height="50" Transition="DownTransition" />

Built in there are several transitions:

  • Default
  • Down
  • Up
  • Right
  • Left
  • RightReplace
  • LeftReplace
  • Custom

StatusBar

<StatusBar Grid.Row="2">
            <StatusBarItem>MahApps.Metro DEMO Application</StatusBarItem>
            <Separator Style="{StaticResource MetroStatusBarSeparator}" />
            <StatusBarItem>Selected Tab:</StatusBarItem>
            <StatusBarItem Content="{Binding ElementName=MainTabControl, Path=SelectedItem.Header, Mode=OneWay}" />
        </StatusBar>

其他

参考:

转载自原文链接, 如需删除请联系管理员。

原文链接:MahApps.Metro使用,转载请注明来源!

0