【发布时间】: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 模式中使用,直到代码隐藏只包含与视图相关的逻辑。