Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to keep code in View code behind?

Tags:

.net

mvvm

wpf

xaml

I've tried to read article WPF/Silverlight: Step By Step Guide to MVVM but I can not understand it completely.

However I've noticied such guideline:

That is your View.xaml.cs that is supposed to have almost no code.

How should I fix my code below? Should I extract my WCF code to some another place? Thanks.

/// <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;
    }
}
like image 951
Oleg Vazhnev Avatar asked Jun 22 '26 12:06

Oleg Vazhnev


1 Answers

Yes, this is bad practice especially from the MVVM perspectives.

Extract all business logic into the ServiceViewModel class, in View just set instance of ViewModel to DataContext:

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

If you have an other class/window which is instantiate this Window you should set ViewModel within it. For instance:

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

So now you can see MVVM in action, in MainWindow XAML file you can use bindings like below:

<!-- 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}" />

In this way your logic stay in ViewModel and decoupled from View.

PS:

I would suggest using ObservableCollection<ConsoleData> for ConsoleData list, benefits are: (MSDN)

ObservableCollection Class

Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

like image 107
sll Avatar answered Jun 25 '26 03:06

sll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!