将代码保留在View代码中是不是很糟糕?

时间:2011-11-11 20:44:18

标签: .net wpf xaml mvvm

我试过阅读文章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;
    }
}

1 个答案:

答案 0 :(得分: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<ConsoleData>用于ConsoleData列表,好处是:(MSDN

  

ObservableCollection类

     

表示在何时提供通知的动态数据集合   项目被添加,删除或刷新整个列表。