This tutorial uses Expression Blend 4. Refer to my previous post for creating ViewModel and data binding.
In E Blend, create a link for the viewModel structure as below:
Edit a name for the DataSource; rename it ‘theViewModel’
After the adding the data source, you can see theViewModel section under ‘Data’. All the properties and methods are exposed in expression blend.
Create some UI elements on the View.
Ready to create some bindings??
Done?! Did you notice the value is seen under the Text property immediately . All data bound UI elements show values at design time.
Binding with the variables is simple; however calling ViewModel’s method on button click (or on other events) needs some additional work. From behaviors section, drag ‘CallMethodAction’ and drog on the ‘Update Info’ Button.
This action adds references to ‘Microsoft.Expression.Interactions.dll’ This action will create a CallMethodAction as child to the button. Edit its Properties as shown below.
DONE! now, when you click the button, the Update Method is called. Editing the textboxes will update the view model variables instantaneously.
Download sample application here. Here is the code for it:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ViewModelDatabinding" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" mc:Ignorable="d" x:Class="ViewModelDatabinding.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:ViewModel x:Key="theViewModel" d:IsDataSource="True"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource theViewModel}}">
<TextBox HorizontalAlignment="Left" Margin="42.4,43.2,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="153.953" Text="{Binding FirstName}"/>
<TextBox HorizontalAlignment="Left" Margin="42.4,92,0,0" TextWrapping="Wrap" Text="{Binding LastName}" VerticalAlignment="Top" Width="153.953"/>
<Slider x:Name="slider" HorizontalAlignment="Left" Margin="42.4,148,0,144" d:LayoutOverrides="Height" Width="153.953" Maximum="100" Minimum="1" SmallChange="1" IsSnapToTickEnabled="True" Value="{Binding Age}"/>
<Label Content="{Binding Value, ElementName=slider}" HorizontalAlignment="Left" Margin="213.6,148,0,140.04" d:LayoutOverrides="Height"/>
<Button Content="Update Info" HorizontalAlignment="Left" Margin="58.4,0,0,32.04" VerticalAlignment="Bottom" Width="95.8" Height="78.76">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction TargetObject="{Binding Mode=OneWay}" MethodName="Update"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</Window>
No comments:
Post a Comment