Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

what would be the MVVM form of this simple test WPF app? (VS2012)

$
0
0

I am trying to grasp the idea of the MVVM pattern for WPF programming -- Data Binding, Commands, Templating.   I put together a very simple WPF app which on the button click event will copy the text content of textBox1 into textBox2  with a little bit of text appended to that.  I built this simple test WPF app based on the winform style -- the controls all have names and the button has a click event. Everything is fairly tightly coupled.  My question is this:  what would the app/guts (xaml, code behind) look like using the MVVM pattern? (code below) I guess I'm requesting if someone could rewrite this app using the MVVM pattern.  I tried to make it very simplistic so I could digest the material more easily.  One other question is this:  am I correct to understand that all WPF apps can be created using the MVVM pattern?  Or would there be some cases (like maybe this test app) where we are resigned to using the winform style?  I mean, maybe MVVM would be overkill for this simple app, but for the sake of learning MVVM, could this app be written using the MVVM pattern?  What would that look like?

--XAML code

<Window x:Class="WpfThing1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"><Grid><Button Name="button1" Content="Button" HorizontalAlignment="Left" Height="33" Margin="82,40,0,0" VerticalAlignment="Top" Width="109" Click="Button_Click"/> <TextBox Name="textBox1" HorizontalAlignment="Left" Height="24" Margin="54,107,0,0" TextWrapping="Wrap" Text="testing" VerticalAlignment="Top" Width="210"/><TextBox Name="textBox2" HorizontalAlignment="Left" Height="23" Margin="54,154,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="210"/></Grid></Window>

--Code Behind

using System;
using System.Windows;

namespace WpfThing1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            button1.Click += (s, f) => { textBox2.Text = Thing1.ReadThing(textBox1.Text); };
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
        }
    }

    class Thing1
    {
        public static string ReadThing(string txt)
        {
            return txt + " -- return Thing";
        }
    }
}
Thanks


Rich P



Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>