【问题标题】:Is it bad to keep code in View code behind?将代码保留在 View code 后面是不是很糟糕?
【发布时间】:2011-11-11 20:44:18
【问题描述】:

我尝试阅读文章WPF/Silverlight: Step By Step Guide to MVVM,但我无法完全理解。

但是我注意到了这样的准则:

那是你的 View.xaml.cs 应该几乎没有代码。

我应该如何修复下面的代码?我应该将我的 WCF 代码提取到另一个地方吗?谢谢。

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        ChannelFactory<IManagementConsole> pipeFactory =
                new ChannelFactory<IManagementConsole>(
                    new NetNamedPipeBinding(),
                    new EndpointAddress(
                        "net.pipe://localhost/PipeManagementConsole"));

        IManagementConsole pipeProxy =
          pipeFactory.CreateChannel();

        List<ConsoleData> datas = new List<ConsoleData>();
        foreach (StrategyDescriptor sd in pipeProxy.GetStrategies())
        {
            datas.Add(pipeProxy.GetData(sd.Id));
        }
        dataGrid1.ItemsSource = datas;
    }
}

【问题讨论】:

标签: .net wpf xaml mvvm


【解决方案1】:

是的,这是一种不好的做法,尤其是从 MVVM 的角度来看。

将所有业务逻辑提取到ServiceViewModel类中,在View中只需将ViewModel的实例设置为DataContext:

 public MainWindow()
 {
      InitializeComponent();
      this.DataContext = new ServiceViewModel();
 }

如果您有其他类/窗口正在实例化此窗口,您应该在其中设置 ViewModel。例如:

MyWindow childWindow = new MyWindow();
childWindow.DataContext = new ServiceViewModel();

所以现在您可以看到 MVVM 正在运行,在 MainWindow XAML 文件中您可以使用如下绑定:

<!-- Considering that ServiceViewModel has 
     public string ServiceName property 
 -->
<TextBlock Text="{Binding ServiceName}" />

<!-- Considering that ServiceViewModel has
     public List<ConsoleData> DataItems property
 -->
<DataGrid ItemsSource="{Binding DataItems}" />

通过这种方式,您的逻辑将保留在 ViewModel 中并与 View 解耦。

PS:

我建议使用ObservableCollection&lt;ConsoleData&gt; 作为 ConsoleData 列表,好处是:(MSDN)

ObservableCollection 类

表示一个动态数据集合,它在何时提供通知 添加、删除或刷新整个列表时。

【讨论】:

  • 谢谢,我可以在 xaml 中设置 DataContext 从而消除最后一行代码吗?如何实现ServiceViewModel?欢迎提供相应文档的链接。
  • @javapowered :查看刚刚更新的答案,基本上您的 ViewModel 应该公开 ObservableCollection&lt;ConsoleData&gt; DataItems 然后将其绑定到 XAML 中,如答案中所示
  • 是的,您可以在 XAML 中设置 DataContext。您需要添加命名空间引用并在“资源”部分创建 ViewModel 类的实例。然后将 DataContext 绑定到该资源。
猜你喜欢
  • 2011-10-06
  • 1970-01-01
  • 2011-09-20
  • 2018-01-20
  • 1970-01-01
  • 2021-06-29
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多