In the following message Multiple views of the same data CodeHulk clarifies some requirements that will allow us to exercise the power of Unity to decouple services.
The XAML code for the HelloWorldView.xaml file:
<UserControl x:Class="HelloWorld.Views.HelloWorldView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HelloWorld"
xmlns:cal="http://www.codeplex.com/CompositeWPF">
<StackPanel>
<TextBlock x:Name="lblResults" HorizontalAlignment="Center">HelloWorld</TextBlock>
<Button Click="btnClick" x:Name="btnOne">Load HelloWorld1</Button>
<Button Click="btnClick" x:Name="btnTwo">Load HelloWorld2</Button>
<ContentControl
cal:RegionManager.RegionName="{x:Static local:RegionNames.HelloWorld}"/>
</StackPanel>
</UserControl>
It produces the following output:
Both buttons subscribe to the same btnClick() method in the above XAML - this is where all the magic happens.
public partial class HelloWorldView : UserControl
{
private IUnityContainer _container;
public HelloWorldView(IUnityContainer container)
{
InitializeComponent();
_container = container;
}
private void btnClick(object sender, System.Windows.RoutedEventArgs e)
{
Button button = sender as Button;
IHelloWorldService service = _container.Resolve<IHelloWorldService>(button.Name);
lblResults.Text = service.GetMessage();
}
}
The button.Name will contain the string "btnOne" or "btnTwo", depending on the button that was clicked. Since a name is provided the container will search the registered IHelloWorldService services and resolve to the applicable class. The classes are defined in the modules RegisterViewsAndServices() method below:
public class HelloWorldModule : IModule
{
private readonly IRegionManager regionManager;
private readonly IUnityContainer container;
public HelloWorldModule(IRegionManager regionManager, IUnityContainer container)
{
this.regionManager = regionManager;
this.container = container;
}
public void Initialize()
{
IRegion mainRegion = this.regionManager.Regions[RegionNames.MainRegion];
RegisterViewsAndServices();
mainRegion.Add( container.Resolve<HelloWorldView>());
}
protected void RegisterViewsAndServices()
{
container
.RegisterType<IHelloWorldService, HelloWorldService1>("btnOne")
.RegisterType<IHelloWorldService, HelloWorldService2>("btnTwo");
}
}
The actual interface, services and button click results follow:
public interface IHelloWorldService
{
string GetMessage();
}
public class HelloWorldService1 : IHelloWorldService
{
public string GetMessage()
{
return "********> Hello World #1 <********";
}
}
public class HelloWorldService2 : IHelloWorldService
{
public string GetMessage()
{
return "======> Hello World #2 <======";
}
}
Source Code: HelloWorld.zip (546.51 kb)
Tags:
compositewpf,
unity,
wpf
Categories:
Unity |
WPF