在ViewModel中绑定RouteEvent,参考国外的大牛,自娱自乐写了一个。
1:XAML 代码
<Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:local="clr-namespace:WpfApplication4" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <CheckBox Width="100" Height="20" Content="Demo CheckBox" local:CheckBoxBehavior.Click="{Binding DemoClick}" /> </Grid> </Window>
2:ViewModel 代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace WpfApplication4 { public class MainWindowsViewModel { #region << Property >> public ICommand DemoClick { get; set; } #endregion #region << Constructor >> public MainWindowsViewModel() { DemoClick = new DeletegateCommand(DemoMethod); } #endregion #region << Method >> public void DemoMethod() { MessageBox.Show("Demo CheckBox Click"); } public bool CanDemoMethod() { return false; } #endregion } }
3:CheckBoxBehavior 代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace WpfApplication4 { public static class CheckBoxBehavior { #region << Property >> public static readonly DependencyProperty ClickProperty = DependencyProperty.RegisterAttached("Click", typeof(ICommand), typeof(CheckBoxBehavior), new UIPropertyMetadata(null,ClickCallBack)); public static ICommand GetClick(DependencyObject obj) { return (ICommand)obj.GetValue(ClickProperty); } public static void SetClick(DependencyObject obj,ICommand cmd) { obj.SetValue(ClickProperty, cmd); } #endregion #region << Method >> private static void ClickCallBack(DependencyObject obj, DependencyPropertyChangedEventArgs e) { if (obj is CheckBox) { var checkBox = obj as CheckBox; if (e.NewValue != null) { checkBox.Click += ClickEvent; } else { checkBox.Click -= ClickEvent; } } } static void ClickEvent(object sender, RoutedEventArgs e) { var cmd = GetClick(sender as CheckBox); if (cmd != null) { cmd.Execute(null); } } #endregion } }
用了这么多代码来实现绑定RouteEvent事件,很多人说着又必要吗。
写这么多代码有意义吗,,,
那请想下为什么用WPF,UI开发的目的是什么?
UI最终的目的是UI和逻辑分离。
写这么多其实就是为了逻辑和Ui分离。