WPF 制作侧边栏菜单之MenuItem
有小伙伴问我有没有做过菜单栏,这我确实没做过,不过现在做还不晚吧,
先来做一个MenuItem,使用MVVM模式写,这样创建菜单的时候,只要绑定datacontext,就ok了,使用极为方便,还可以自定义颜色相关的属性。
先来看一下效果:
下面就来看看代码喽:
首先创建一个自定义控件类:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Windows;using System.Windows.Controls;using System.Windows.Markup;using System.Windows.Media;
namespace WPFDemos{ [DefaultProperty("MenuItems")] [ContentProperty("MenuItems")] [TemplatePart(Name = LB, Type = typeof(ListBox))] public class SideMenuItem : Control { private const string LB = "LB"; private ListBox _listBox; public bool IsExpanded { get { return (bool)GetValue(IsExpandedProperty); } set { SetValue(IsExpandedProperty, value); } } public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register("IsExpanded", typeof(bool), typeof(SideMenuItem), new PropertyMetadata(false));
public List<object> MenuItems { get { return (List<object>)GetValue(MenuItemsProperty); } set { SetValue(MenuItemsProperty, value); } } public static readonly DependencyProperty MenuItemsProperty = DependencyProperty.Register("MenuItems", typeof(List<object>), typeof(SideMenuItem), new PropertyMetadata(default(List<object>)));
public Brush ToggleBackground { get { return (Brush)GetValue(ToggleBackgroundProperty); } set { SetValue(ToggleBackgroundProperty, value); } } public static readonly DependencyProperty ToggleBackgroundProperty = DependencyProperty.Register("ToggleBackground", typeof(Brush), typeof(SideMenuItem), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(0x2d, 0x2d, 0x30))));
public Brush MenuItemBackground { get { return (Brush)GetValue(MenuItemBackgroundProperty); } set { SetValue(MenuItemBackgroundProperty, value); } } public static readonly DependencyProperty MenuItemBackgroundProperty = DependencyProperty.Register("MenuItemBackground", typeof(Brush), typeof(SideMenuItem), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(0x16, 0x18, 0x1D))));
public Brush MenuItemSelectedBackground { get { return (Brush)GetValue(MenuItemSelectedBackgroundProperty); } set { SetValue(MenuItemSelectedBackgroundProperty, value); } } public static readonly DependencyProperty MenuItemSelectedBackgroundProperty = DependencyProperty.Register("MenuItemSelectedBackground", typeof(Brush), typeof(SideMenuItem), new PropertyMetadata(Brushes.Green));
public static readonly RoutedEvent MenuItemSelectedChangedEvent = EventManager.RegisterRoutedEvent("MenuItemSelectedChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SideMenuItem));