Just Code‎ > ‎

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

posted Mar 8, 2013, 7:51 AM by Peter Henell   [ updated Mar 8, 2013, 7:52 AM ]

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; }
        
    }
}
Comments