While I was learning inversion of control from autofacs example, I got idea to write my application which I will use to "feel" IoC.
So, idea was to have two buttons where one will write a message to console, and second one will write same message to text box window. Idea looked simple, but... Problem was because I wanted to follow MVVM pattern, I have created command, binded click event, then all I had to do was to change textbox text, and that was actually a problem, I couldn't find a way simply to change the value...
Only way which I found was to send an object as parameter, something like:
CommandParameter="{Binding ElementName=IoCmessageDisplayTextBox}"
Where IoCmessageDisplayTextBox is text box on which I want to display my message.
So, here is my XAML:
<Window x:Class="IoCtest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:IoCtest" Title="MainWindow" Height="350" Width="525"> <Window.DataContext><local:ClickModel /> </Window.DataContext> <Grid OverridesDefaultStyle="True"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="30"></RowDefinition> </Grid.RowDefinitions> <TextBox x:Name="IoCmessageDisplayTextBox" Grid.Row="0" Grid.Column="0" TextWrapping="Wrap" Text="TextBox" AcceptsReturn="True" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"/> <Button Grid.Row="1" Content="Write to memo" Command="{Binding MyClick}" CommandParameter="{Binding ElementName=IoCmessageDisplayTextBox}" Height="30" VerticalAlignment="Bottom"></Button> </Grid> </Window>
Since I already explained how to create button click event using ICommand here, I will not do it again, I will just keep focus on method which will be executed when user clicks button.
Method looks like this:
public void ShowMessage(object obj) { TextBox IoCmessageDisplayTextBox = new TextBox(); IoCmessageDisplayTextBox = (TextBox)obj; IoCmessageDisplayTextBox.Text = "Hello world!"; }
As you can see I had to convert object which I sent as parameter to TextBox, and then I was able to change text property of my TextBox.
Example you download from here, project is prepared for IoC learning, that is why it is more dirty then usual :) I hope that results of my learning I will post soon.