【问题标题】:Wpf Mvvm creating a Dialog using a behaviorWpf Mvvm 使用行为创建对话框
【发布时间】:2015-10-27 10:01:01
【问题描述】:

我目前正在审查一个 Wpf Mvvm 项目。我注意到在某些地方,正在使用一种行为创建新的对话框。

让我们先看一下代码:在视图中,按钮的属性是这样设置的。

  <Button Grid.Column="0"
          behaviors:OpenFileClickBehavior.IsOpenFileButton="True"
          behaviors:OpenFileClickBehavior.FileOpenDialogFilter="All files (*.*)|*.*" />

还有一个静态行为类:

 public static class OpenFileClickBehavior
 {
        public const string IsOpenFileButtonPropertyName = "IsOpenFileButton";

        public static readonly DependencyProperty IsOpenFileButtonProperty = DependencyProperty.RegisterAttached(
        IsOpenFileButtonPropertyName,
        typeof(bool),
        typeof(OpenFileClickBehavior),
        new UIPropertyMetadata(false, OnIsOpenFileButtonPropertyChanged));

        public static readonly DependencyProperty OpenFileDialogFilterProperty = DependencyProperty.RegisterAttached(
        "OpenFileDialogFilterProperty",
        typeof(String),
        typeof(OpenFileClickBehavior),
        new UIPropertyMetadata(String.Empty));

        private static void OnIsOpenFileButtonPropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
        {
            Button button = dpo as Button;
            if (button != null)
            {
                if ((bool)args.NewValue)
                {
                    button.Click += ButtonClick;
                }
                else
                {
                    button.Click -= ButtonClick;
                }
            }
        }

     private static void ButtonClick(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        Attachment attachment = button.DataContext as Attachment;
        String filter = GetFileOpenDialogFilter(button);

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = filter;

        bool? dialogResult = ofd.ShowDialog();

        if (dialogResult != null && dialogResult == true)
        {
            attachment.Path = ofd.FileName;
        }
    }

所以按钮点击事件在这个类中被注册/取消注册和处理。

我知道 mvvm 建议视图模型不应该知道视图并且视图的代码隐藏文件应该是空的。此解决方案既没有代码隐藏在视图中,也没有从视图模型创建视图。我想知道这种方法是否以任何其他方式破坏了 mvvm 模式,或者有任何缺点。

提前谢谢

【问题讨论】:

  • 嗨,你应该把这个发到codereview.stackexchange.com。 StackOverflow 不太适合这类问题。
  • 我知道 mvvm 建议......视图的代码隐藏文件应该是空的 - MVVM 从来没有建议过。代码隐藏可以在 MVVM 模式中使用,直到代码隐藏只包含与视图相关的逻辑。

标签: c# wpf mvvm


【解决方案1】:

行为将部分功能封装到可重用组件中,稍后我们可以将其附加到视图中的元素。重点是可重用。可以在代码隐藏中或直接在 XAML 中执行相同的代码,因此对于行为而言,这并不是什么神奇的事情。行为还具有保持 MVVM 模式完整的好处,因为我们可以将代码从代码隐藏移动到行为。一个例子是,如果我们想要滚动 ListBox 中的选定项,并且选定项是从代码中选择的,例如从搜索函数中选择。 ViewModel 不知道视图使用 ListBox 来显示列表,因此它不能用于滚动所选项目。而且我们不想将代码放在代码隐藏中,但是如果我们使用一种行为,我们可以解决这个问题并创建一个可以再次使用的可重用组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2010-12-12
    • 2011-02-17
    • 2010-12-20
    • 2021-05-31
    相关资源
    最近更新 更多