代码之家  ›  专栏  ›  技术社区  ›  Irwin M. Fletcher

XAML或代码隐藏中的事件处理程序

  •  7
  • Irwin M. Fletcher  · 技术社区  · 16 年前

    我是Silverlight和XAML的新手。在尝试学习语法和最佳实践的同时,我仍然在一些实现事件处理程序的方式上遇到了差异(至少在我看来是这样)。

    在一个 example

    <UserControl x:Class="DragAndDropSimple.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Width="400" Height="300">
      <Canvas x:Name="rootCanvas"
      Width="640"
      Height="480"
      Background="Gray"
      >
        <!-- You can drag this rectangle around the canvas. -->
        <Rectangle
        MouseLeftButtonDown="Handle_MouseDown"
        MouseMove="Handle_MouseMove"
        MouseLeftButtonUp="Handle_MouseUp"
        Canvas.Left="30" Canvas.Top="30" Fill="Red"
        Width="50" Height="50" />
      </Canvas>
    
    </UserControl>
    

    但是,在其他应用程序中设置鼠标处理程序的位置 code 我在代码隐藏中看到了这种方法:

     public Window1()
            {
                InitializeComponent();
    
                TransformGroup group = new TransformGroup();
    
                ScaleTransform xform = new ScaleTransform();
                group.Children.Add(xform);
    
                TranslateTransform tt = new TranslateTransform();
                group.Children.Add(tt);
    
                image.RenderTransform = group;
    
                image.MouseWheel += image_MouseWheel;
                image.MouseLeftButtonDown += image_MouseLeftButtonDown;
                image.MouseLeftButtonUp += image_MouseLeftButtonUp;
                image.MouseMove += image_MouseMove;
            }
    

    我假设MSDN上的示例是推荐的方法,但是,我倾向于喜欢第二种方法。

    4 回复  |  直到 6 年前
        1
  •  4
  •   Parrots    16 年前

    除非我需要动态修改对象的事件处理程序,否则我更喜欢在XAML本身中定义它。

        2
  •  5
  •   AnthonyWJones    16 年前

    在第一种方法中,有两个“代码站点”

    1. 定义UI元素的XAML
    2. 代码隐藏中的事件处理程序过程

    第二种是3个“代码站点”

    1. 定义UI元素的XAML
    2. 代码隐藏中的事件处理程序过程

    就我个人而言,我更喜欢第一种方法。如果我删除一个元素,我只需要找到需要删除的事件处理程序,那么我也不需要编辑类构造函数。

        3
  •  2
  •   Community Mohan Dere    9 年前

    最佳做法:使用 MVVM ICommands

    除此之外,在xaml中声明性地设置事件处理程序或通过构造函数中的代码设置事件处理程序没有“最佳实践”。这取决于你。

    然而,我认为,大多数人都希望在xaml中看到声明,因为这就是您设计UI的地方。