WPF MVVM中将frameElement事件绑定到viewmodel处理程序的“正确”方法是什么?

时间:2009-08-21 15:36:32

标签: c# .net wpf events mvvm

所以这就是我的困境,我想在我的视图模型上处理视图事件,麻烦的是,为了添加一个事件处理程序,我的视图必须有一个代码隐藏文件,因此必须设置一个类属性。我99%肯定这是一个坏主意,而且说实话,我甚至不知道该怎么做(除了显而易见的x:Class =“”部分)这样做的正确方法是什么MVVM应用程序?

<ResourceDictionary>
    <DataTemplate DataType="{x:Type vm:OutletViewModel}">
        <Button Click="IHaveNoBinding">
    </DataTemplate>
</ResourceDictionary>

4 个答案:

答案 0 :(得分:4)

使用commands

<Button Command="{Binding ACommandOnYourViewModel}"/>

请参阅我的this post,了解您可以在视图模型中使用的有用命令实现。

假设您无法使用命令,请使用attached command behaviors

答案 1 :(得分:2)

我使用附加行为。附加行为基本上将事件转换为命令。查看此链接以获取示例:

http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

以下是TextChangedBehavior的代码。

 public static class TextChangedBehavior
  {
    public static readonly DependencyProperty TextChangedCommandProperty =
        DependencyProperty.RegisterAttached("TextChangedCommand",
                                            typeof(ICommand),
                                            typeof(TextChangedBehavior),
                                            new PropertyMetadata(null, TextChangedCommandChanged));

    public static ICommand GetTextChangedCommand(DependencyObject obj)
    {
      return (ICommand)obj.GetValue(TextChangedCommandProperty);
    }

    public static void SetTextChangedCommand(DependencyObject obj, ICommand value)
    {
      obj.SetValue(TextChangedCommandProperty, value);
    }

    private static void TextChangedCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      TextBoxBase textBox = obj as TextBoxBase;

      if (textBox != null)
      {
        textBox.TextChanged += new TextChangedEventHandler(HandleTextChanged);
      }
    }

    private static void HandleTextChanged(object sender, TextChangedEventArgs e)
    {
      TextBox textBox = sender as TextBox;
      if (textBox != null)
      {
        ICommand command = GetTextChangedCommand(textBox);
        command.Execute(textBox.Text);
      }
    }
  }

XAML:

<TextBox behavior:TextChangedBehavior.TextChangedCommand="{Binding TextChangedCommand}" />

答案 2 :(得分:1)

通常我不会将附加的行为模式用于这样的简单事情。作为一名顾问,我发现它使新开发人员的事情变得复杂。

那么当没有命令可用时你如何处理控制交互。准备好从地板上挑选自己:-)我经常会使用背后的代码。后面的代码中的事件处理程序处理事件,它从事件args收集它需要的任何数据,然后将请求转发给View Model。这样做不会造成太多损失,因为大多数不支持ICommand的东西都无法利用hide / show / enable / disable。

但是有一些规则。后面的代码只能用于控制转发到View Model。只要您不将事件参数直接传递给View Model,我认为以这种方式使用事件是可以的。这件事的事实是在大规模的应用程序中,你不能总是摆脱代码隐藏。如果您按预期使用它们,即页面控件,我认为这样做没有坏处。

答案 3 :(得分:0)

背后的代码根本不是一件坏事。有足够的场景你不能使用WPF数据绑定(例如PasswordBox),然后你必须在文件后面创建一个代码。

如何在没有绑定的情况下使用PasswordBox显示在此项目的ViewModel示例中:

WPF应用框架(WAF)

http://waf.codeplex.com