This is my trial for applying View-ViewModel concept in WPF Windows application. I do not have a Model for this sample so omitting that word ;)

This is the XAML code which I used. Here I tried to do text binding with a TextBox and Command binding with a Button.

File 1: Window1.xaml

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=System.Core"
    Title="Window1" Height="300" Width="300" Name="Window1">
    <Grid>
        <Button Margin="121,129,82,110" Name="Button1" 
		Command="{Binding ClickCommand}">Button</Button>
        <TextBox Height="23" Margin="76,0,82,63" Name="TextBox1" 
		VerticalAlignment="Bottom" Text="{Binding mytext}" />
    </Grid>
</Window>

 

File 2: Window1.xaml.vb

Class Window1
    Private Sub Window1_Loaded(ByVal sender As System.Object, 
	ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Dim vm As New ViewModel
        vm.mytext = "test"
        Window1.DataContext = vm
    End Sub
End Class

And here is the VB.NET code:

File 3: ViewModel.vb

Imports System.ComponentModel
 
Public Class ViewModel
    Implements INotifyPropertyChanged
    Public _mytext As String
    Public Property mytext() As String
        Get
            Return _mytext
        End Get
        Set(ByVal value As String)
            _mytext = value
        End Set
    End Property
 
    Public Property ClickCommand() As ICommand
        Get
            Return New ClickCommando(Me)
        End Get
        Set(ByVal value As ICommand)
 
        End Set
    End Property
 
    Public Event PropertyChanged As PropertyChangedEventHandler 
	Implements INotifyPropertyChanged.PropertyChanged
 
End Class
 
Public Class ClickCommando
    Implements ICommand
 
    Private _vm As ViewModel
 
    Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
        MessageBox.Show(_vm.mytext)
    End Sub
 
    Public Function CanExecute(ByVal parameter As Object) As Boolean 
	Implements ICommand.CanExecute
        Return True
    End Function
 
    Public Event CanExecuteChanged As EventHandler 
	Implements ICommand.CanExecuteChanged
 
    Public Sub New(ByVal vm As ViewModel)
        _vm = vm
    End Sub
 
End Class
VN:F [1.1.6_502]
Rating: 5.0/5 (1 vote cast)
Share:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • DotNetKicks
  • LinkedIn
  • Live
  • MySpace
  • StumbleUpon
  • Technorati

Related posts:

  1. Manipulate TFS from VB.NET – a starter
  2. Get currently logged in user from a service running under LocalSystem account
  3. Find your lucky number in c#
  4. WPF – Cube rotation - animation
  5. A simple ISAPI extension with C#