by Corrado Cavalli via Corrado's BLogs on 5/6/2011 6:56:20 AM
I’m a longtime supporter of Laurent Bugnion’s MVVM Light Toolkit and I love using it together with my favorite IOC Container NInject, one of the most “boring” area is creating the class that exposes ViewModel instances in a design time way: the famous ViewModelLocator class. Now that Silverlight5 has custom markup extensions I thought: what about using it to simplify View vs ViewModel lookup?
Here’s my attempt, let’s start with a simple ViewModel (nothing really new here, just to give you a complete scenario)
public class MyViewModel : ViewModelBase { private string message; public MyViewModel() { this.SaveCommand = new RelayCommand(this.HandleCommand); this.Message = "Go!"; } public string Message { get { return this.message; } set { if (value != this.message) { this.message = value; this.RaisePropertyChanged(); } } } public RelayCommand SaveCommand { get; private set; } private void HandleCommand() { MessageBox.Show("Saving..."); } }
public class ServiceProvider : NinjectModule { public ServiceProvider() { this.Kernel = new StandardKernel(this); } public override void Load() { this.Bind<MyViewModel>().ToSelf(); } }
public class ViewModelLocator{ private static ViewModelLocator instance; public static ViewModelLocator Instance { get { if (instance == null) { instance = new ViewModelLocator(); } return instance; } } public ServiceProvider Resolver { get; set; } public T Get<T>() { return this.Resolver.Kernel.Get<T>(); }}
public App(){ ViewModelLocator.Instance.Resolver = new ServiceProvider(); InitializeComponent();}
public class ViewModelProviderExtension : IMarkupExtension<object> { public string Type { get; set; } public object ProvideValue(IServiceProvider serviceProvider) { if (this.Type != null) { IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver; Type type = xamlTypeResolver.Resolve(this.Type); MethodInfo m = typeof(ViewModelLocator).GetMethod("Get").MakeGenericMethod(type); return m.Invoke(ViewModelLocator.Instance, null); } return null; } }
<Grid x:Name="LayoutRoot" DataContext="{my:ViewModelProvider Type=my:MyViewModel}" Background="White"> <Button Content="{Binding Message}" Height="40" Command="{Binding SaveCommand}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" /> </Grid>
Original Post: Pairing View and ViewModel using Silverlight5 Custom Markup Extension
The content of the postings is owned by the respective author. Silverlight Feeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on Silverlight Feeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.