WPF实战学习笔记07-设置备忘录以及设置界面

设置备忘录以及设置界面

设置备忘录界面

同待办事项,相关名字改掉,类tododto改成memodto即可

添加文件

./Views/SkinView.xaml

./Views/SysSetView.xaml

./Views/AboutView.xaml

./ViewModels/SkinViewModel.cs

./ViewModels/SysSetViewModel.cs

./ViewModels/AboutViewModel.cs

添加子区域

添加变量
  • PrismManager.cs

    public static readonly string SettingsViewRgionName = "SettingsViewRgion";
    
注册区域
  • SettingsView.xaml

    <ContentControl prism:RegionManager.RegionName="{x:Static ext:PrismManager.SettingsViewRgionName}" />
    

SettingsView.xaml

从MainView.xaml处复制过来

<UserControl
    x:Class="Mytodo.Views.SettingsView"
    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:ext="clr-namespace:Mytodo.Extensions"
    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:local="clr-namespace:Mytodo.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
    xmlns:prism="http://prismlibrary.com/"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="AUTO" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock FontSize="26" Text="设置" />
        <DockPanel Grid.Row="1" MinWidth="220">
            <ListBox
                x:Name="menuBar"
                MinWidth="200"
                Margin="10,10"
                HorizontalContentAlignment="Stretch"
                DockPanel.Dock="Left"
                ItemContainerStyle="{StaticResource MyListboxItemStyle}"
                ItemsSource="{Binding MenuBars}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="SelectionChanged">
                        <i:InvokeCommandAction Command="{Binding NavigateCmd}" CommandParameter="{Binding ElementName=menuBar, Path=SelectedItem}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <md:PackIcon Kind="{Binding Icon}" />
                            <TextBlock
                                Margin="10,0"
                                FontFamily="微软雅黑"
                                Text="{Binding Title}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
            <ContentControl prism:RegionManager.RegionName="{x:Static ext:PrismManager.SettingsViewRgionName}" />
        </DockPanel>
    </Grid>
</UserControl>

SettingsViewModel.cs

using Mytodo.Common.Models;
using Mytodo.Extensions;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.ViewModels
{
    public class SettingsViewModel:BindableBase
    {
        public SettingsViewModel(IRegionManager rgm)
        {
            regionManager = rgm;

            CreatMenuBar();

            //关联命令与操作
            NavigateCmd = new DelegateCommand<MenuBar>(Navigate);
        }

        #region 菜单栏绑定变量定义以及初始化

        private ObservableCollection<MenuBar> menuBars;

        public ObservableCollection<MenuBar> MenuBars
        {
            get { return menuBars; }
            set { menuBars = value; RaisePropertyChanged(); }
        }

        void CreatMenuBar()
        {
            MenuBars = new ObservableCollection<MenuBar>();

            MenuBars.Add(new MenuBar { Icon = "Home", NameSpace = "SkinView", Title = "个性化" });
            MenuBars.Add(new MenuBar { Icon = "FormatListChecks", NameSpace = "SysSetView", Title = "系统设置" });
            MenuBars.Add(new MenuBar { Icon = "Notebook", NameSpace = "AboutView", Title = "关于更多" });
        }

        #endregion



        #region 定义打开命令变量以及初始化命令操作函数
        /// <summary>
        /// 定义导航变量
        /// </summary>
        private readonly IRegionManager regionManager;
        /// <summary>
        /// 定义命令
        /// </summary>
        public DelegateCommand<MenuBar> NavigateCmd { get; private set; }

        /// <summary>
        /// 定义导航操作
        /// </summary>
        /// <param name="obj"></param>
        private void Navigate(MenuBar obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
                return;
            regionManager.Regions[PrismManager.SettingsViewRgionName].RequestNavigate(obj.NameSpace);
        }

        #endregion
    }
}

添加App.xaml,关联view和viewmodel

//建立view与viewmodel的关系
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation<AboutView, AboutViewModel>();
    containerRegistry.RegisterForNavigation<SysSetView, SysSetViewModel>();
    containerRegistry.RegisterForNavigation<SkinView, SkinViewModel>();
    containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
    containerRegistry.RegisterForNavigation<TodoView, TodoViewModel>();
    containerRegistry.RegisterForNavigation<MemoView, MemoViewModel>();
    containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();
}

编辑skinview

skinview.xaml

主要从materialDesignDemo项目复制,需要更改项目名称,引用空间,另需要添加转换器以及对应的转换器资源key

<UserControl
    x:Class="Mytodo.Views.SkinView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Assists="clr-namespace:Mytodo.Common.Assists"
    xmlns:converters="clr-namespace:Mytodo.Common.Converters"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:Mytodo.Views"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    xmlns:materialDesignColors="clr-namespace:MaterialDesignColors;assembly=MaterialDesignColors"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <UserControl.Resources>
        <converters:ColorToBrushConverter x:Key="ColorToBrushConverter" />
        <converters:MultiValueEqualityConverter x:Key="MultiValueEqualityConverter" />
        <DataTemplate x:Key="SwatchColorTemplate" DataType="{x:Type Color}">
            <Button
                Width="40"
                Height="40"
                Background="{Binding Converter={StaticResource ColorToBrushConverter}}"
                Command="{Binding DataContext.ChangeHueCommand, RelativeSource={RelativeSource AncestorType=local:SkinView}}"
                CommandParameter="{Binding}">
                <Button.Style>
                    <Style BasedOn="{StaticResource MaterialDesignRaisedButton}" TargetType="Button">
                        <Setter Property="BorderThickness" Value="0" />
                        <Setter Property="Margin" Value="1,1,0,0" />
                        <Setter Property="Tag" Value="0" />
                        <Setter Property="Assists:ButtonAssist.UniformCornerRadius" Value="0" />
                        <Setter Property="materialDesign:ElevationAssist.Elevation" Value="Dp0" />
                        <Setter Property="materialDesign:RippleAssist.IsDisabled" Value="True" />
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Trigger.EnterActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <DoubleAnimation
                                                Storyboard.TargetProperty="(Assists:ButtonAssist.UniformCornerRadius)"
                                                To="8"
                                                Duration="0:0:0.18" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.EnterActions>

                                <Trigger.ExitActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <DoubleAnimation
                                                Storyboard.TargetProperty="(Assists:ButtonAssist.UniformCornerRadius)"
                                                From="8"
                                                Duration="0:0:0.18" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.ExitActions>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Button.Style>
            </Button>
        </DataTemplate>
    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <StackPanel Margin="30" Orientation="Horizontal">
            <TextBlock
                VerticalAlignment="Center"
                FontSize="30"
                Text="亮" />

            <ToggleButton
                Margin="8,0,16,0"
                FontSize="20"
                IsChecked="{Binding IsDarkTheme}" />

            <TextBlock
                VerticalAlignment="Center"
                FontSize="30"
                Text="暗" />
        </StackPanel>
        <ItemsControl
            Grid.Row="1"
            Width="auto"
            HorizontalAlignment="Center"
            ItemsSource="{Binding Swatches}">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type materialDesignColors:ISwatch}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock
                            Width="80"
                            VerticalAlignment="Center"
                            Text="{Binding Name, Mode=OneTime}" />
                        <ItemsControl ItemTemplate="{StaticResource SwatchColorTemplate}" ItemsSource="{Binding Hues}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <VirtualizingStackPanel Orientation="Horizontal" />
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                        </ItemsControl>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</UserControl>

skinviewmodel.cs

都是从materialDesignDemo的colortool对应的.cs中复制过来,除了Swatches

using MaterialDesignColors;
using MaterialDesignColors.ColorManipulation;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;

namespace Mytodo.ViewModels
{
    class SkinViewModel : BindableBase
    {
        public IEnumerable<ISwatch> Swatches { get; } = SwatchHelper.Swatches;
        private readonly PaletteHelper paletteHelper = new PaletteHelper();
        private bool _isDarkTheme;
        public bool IsDarkTheme
        {
            get => _isDarkTheme;
            set
            {
                if (SetProperty(ref _isDarkTheme, value))
                {
                    ModifyTheme(theme => theme.SetBaseTheme(value ? Theme.Dark : Theme.Light));
                }
            }
        }

        public IEnumerable<Contrast> ContrastValues => Enum.GetValues(typeof(Contrast)).Cast<Contrast>();
        private static void ModifyTheme(Action<ITheme> modificationAction)
        {
            var paletteHelper = new PaletteHelper();

            ITheme theme = paletteHelper.GetTheme();

            modificationAction?.Invoke(theme);

            paletteHelper.SetTheme(theme);
        }

        public DelegateCommand<object> ChangeHueCommand { get; private set; }

        public SkinViewModel()
        {
            ChangeHueCommand = new DelegateCommand<object>(ChangeHue);
        }

        private void ChangeHue(object obj)
        {
            var hue = (Color)obj;
            ITheme theme = paletteHelper.GetTheme();
            theme.PrimaryLight = new ColorPair(hue.Lighten());
            theme.PrimaryMid = new ColorPair(hue);
            theme.PrimaryDark = new ColorPair(hue.Darken());
            paletteHelper.SetTheme(theme);
        }
    }
}
ColorToBrushConverter.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace Mytodo.Common.Converters
{
    [ValueConversion(typeof(Color), typeof(Brush))]
    public class ColorToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Color color)
            {
                return new SolidColorBrush(color);
            }
            return Binding.DoNothing;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is SolidColorBrush brush)
            {
                return brush.Color;
            }
            return default(Color);
        }
    }
}

MultiValueEqualityConverter.CS
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace Mytodo.Common.Converters
{
    public class MultiValueEqualityConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return values?.All(o => o?.Equals(values[0]) == true) == true || values?.All(o => o == null) == true;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

其他

其他的view自己定义就可以,这里不再展开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值