WPF - Create a viewmodel from XAML with parameters in the vm constructor

Post date: Mar 8, 2013 3:51:53 PM

View:

<Window xmlns:my="clr-namespace:SQLTestDataGenerationTool.View" x:Class="SQLTestDataGenerationTool.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:SQLTestDataGenerationTool.ViewModel" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <ObjectDataProvider ObjectType="vm:TableViewModel" x:Key="tableVM" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <ObjectDataProvider.ConstructorParameters> <sys:String>typeName</sys:String> <sys:Int32>42</sys:Int32> </ObjectDataProvider.ConstructorParameters> </ObjectDataProvider> </Window.Resources> <Grid DataContext="{StaticResource ResourceKey=tableVM}"> <StackPanel> <TextBlock Text="{Binding Path=Name}" /> <TextBlock Text="{Binding Path=Number}" /> </StackPanel> </Grid> </Window>

ViewModel:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using DatabaseMetadata.Entities;namespace SQLTestDataGenerationTool.ViewModel { public class TableViewModel : ViewModelBase { public TableViewModel(string s, int a) { Name = s; Number = a; } public string Name { get; set; } public int Number { get; set; } }}