Silverlight startup parameters pass to viewmodel - silverlight

im passing my webservice url to my silverlight application via the parameters.
when my application launches it creates the viewmodel for the mainpage before it application_startup event is fired.
in my viewmodel constructor i have a call to my serviceagent to load some data from the webservice, but the webservice url is not initialised yet due the the viewmodel being constructed before the application_startup event is raised. whats the best way to get around this. Its a friday evening and my brain seems to be pretty fried trying to think of a good solution.
An instance of the ViewModelLocator is created in the app.xaml
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
Then in the ViewModelLocator constructor there is a call to create the main page
public ViewModelLocator()
{
CreateMain();
}
public static void CreateMain()
{
if (_main == null) _main = new MainViewModel();
}
and in my MainViewModel i make a call to my serviceagent
public MainViewModel() : this(new MyServiceAgent()) { }
public MainViewModel(IMyServiceAgent myServiceAgent)
{
if (IsInDesignMode)
{
}
else
{
ServiceAgent = myServiceAgent;
ServiceAgent.GetData();
RegisterMessageListeners();
WireUpCommands();
}
}
App.xaml.cs
public App()
{
Startup += Application_Startup;
Exit += Application_Exit;
UnhandledException += Application_UnhandledException;
InitializeComponent();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.InitParams != null && e.InitParams.Count > 0)
ParseInitParams(e.InitParams);
RootVisual = new MainPage();
DispatcherHelper.Initialize();
}
Cheeers

to fix my issue i had to remove the line of code from the viewmodellocator constructor that was initialising the MainViewModel
public ViewModelLocator()
{
//CreateMain();
}

Related

ICommand with MVVM in WPF

I am new to MVVM and WPF, trying to use ICommand in WPF and MVVM. Below is the code.
Can someone please help to know why the below code is not working, means nothing happens on button click.
Appreciate your help.
View
<Grid>
<Button Height="40" Width="200" Name="button1" Command="{Binding Path=Click}">Click Me</Button>
</Grid>
App.xaml.cs
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow mainWindow = new MainWindow();
MainWindowViewModel vm = new MainWindowViewModel();
mainWindow.DataContext = vm;
}
}
MainWindowViewModel.cs
namespace TestWPFApplication.ViewModel
{
public class MainWindowViewModel
{
private ICommand _click;
public ICommand Click
{
get
{
if (_click == null)
{
_click = new CommandTest();
}
return _click;
}
set
{
_click = value;
}
}
private class CommandTest : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show("Hi! Test");
}
}
}
}
It looks like your OnStartup method is instantiating a MainWindow and never showing it. You probably have the StartupUri set in XAML which is creating a different MainWindow with the data context not set.
You could remove the StartupUri and call mainWindow.Show(). Alternatively, you could get rid of the OnStartup method and set up the data context in the main window's constructor.
You don't need to initialize this Window in OnStartup.
In MainWindow constructor after Initialize create instance of ViewModel and it should work.

Calling a method of a UserControl somewhere in MVVM

I have the following scenario:
I have a user control, let's say UserControl.xaml
In the code behind of this control I have the method DoSomething()
I have viewmodel for this control UserControlViewModel.cs
I need to call usercontrol's DoSomething() method somewhere. Any ideas how to accomplish this?
Thanks!
If I really had to do this, then using the DataContextChanged event may help.
Here's a solution with hopefully minimal coupling between the view and the view-model.
public partial class MainWindow : IMainWindow
{
public MainWindow()
{
this.DataContextChanged += this.MainWindowDataContextChanged;
this.InitializeComponent();
}
private void MainWindowDataContextChanged(object sender,
DependencyPropertyChangedEventArgs e)
{
var vm = this.DataContext as IMainWindowViewModel;
if (vm != null)
{
vm.View = this;
}
}
public void DoSomething()
{
Debug.WriteLine("Do something in the view");
}
}
public interface IMainWindow
{
void DoSomething();
}
public class MainWindowViewModel : IMainWindowViewModel
{
public MainWindowViewModel()
{
this.DoSomethingCommand = new RelayCommand(this.DoSomething);
}
public ICommand DoSomethingCommand { get; set; }
private void DoSomething()
{
Debug.WriteLine("Do something in the view model");
var view = this.View;
if (view != null)
{
view.DoSomething();
}
}
public IMainWindow View { get; set; }
}
public interface IMainWindowViewModel
{
IMainWindow View { get; set; }
}
You really should be using an MVVM framework if you're doing MVVM. A framework would provide a mechanism from which you can invoke a verb (method) on your view model from your view. Caliburn.Micro for example provides Actions.
It sounds as though your application is incorrectly structured.
What does
DoSomething()
do, that isn't reacting to a change in a bound property of the ViewModel?
If you really need to trigger something in the code behind of the View from the ViewModel, use a messaging handler such as the one in the Galasoft MVVMLight framework.

MVVM Light pass parameters to child view model

I am new to MVVM and WPF.
I am using MVVM Light to make an application which contains a DataGrid within a window, which has a view model (MainViewModel) and another window for adding and editing records in the DataGrid, that also has its own view model (EditViewModel).
What I am worried about is the approach I am using to open the Add/Edit window from the MainViewModel. In the MainViewModel I have a property SelectedItem, which is bound to the SelectedItem property of the DataGrid and an IsEdit boolean property that indicates if the Add/Edit window should be launched in Add or Edit mode.
When the Add/Edit window gets opened in edit mode, in the constructor of its view model I have the following line:
MainViewModel mainViewModel = ServiceLocator.Current.GetInstance<MainViewModel>();
That obviously retrieves the current instance of the MainViewModel, which works perfectly fine, but I am not really sure it is the best way to do this.
Also if I have more than one instances of the Main window, that use the same MainViewModel instance and I open an instance of the Add/Edit window from both of them, the Add/Edit windows are going to get data from the same instance of the MainViewModel which may be a problem.
If I try to create a new instance of MainViewModel for each MainWindow I open, then I don't know how to pass the instance of the currently used MainViewModel to the EditViewModel.
I hope I made clear what I need to do. Tell me if I have missed something and I will add it:)
Thanks in advance
Hi if I havent misunderstood your problem incorrect you can do it this way:
Since i need IsRequired dependency Property in both MainView and EditView i created a class that extends Window class
public class ExtendedWindow:Window
{
public static readonly DependencyProperty IsRequiredProperty = DependencyProperty.Register("IsRequired", typeof(bool), typeof(ExtendedWindow));
public bool IsRequired
{
get { return (bool)GetValue(IsRequiredProperty); }
set { SetValue(IsRequiredProperty, value); }
}
}
MainView and ViewModel
public partial class MainWindow:ExtendedWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
EditView editView = new EditView();
**((EditViewModel)editView.DataContext).IsRequired = this.IsRequired;**
editView.Show();
}
}
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
IsRequired = true;
}
private bool isRequired;
public bool IsRequired
{
get { return isRequired; }
set { isRequired = value; Notify("IsRequired"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
EditView and ViewModel
public partial class EditView:ExtendedWindow
{
public EditView()
{
InitializeComponent();
DataContext = new EditViewModel();
}
}
public class EditViewModel : INotifyPropertyChanged
{
private bool isRequired;
public bool IsRequired
{
get { return isRequired; }
set { isRequired = value; Notify("IsRequired"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
This is just kind of dummy but can give you idea how you can do it. I have tried it in dummy and its working fine.

Using AutoFac BootStrapper?

I am attempting to translate a WPF example of IOC using StructureMap into Silverlight using AutoFac
This is proving to be very difficult
I have got a static BootStrapper class defined
public class BootStrapper
{
public static IContainer BaseContainer { get; private set; }
public static FlexContractStructureViewModel FlexContractStructureViewModel()
{
return BaseContainer.Resolve<FlexContractStructureViewModel>();
}
public static void Build()
{
if (BaseContainer == null)
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes();
BaseContainer = builder.Build();
}
}
static BootStrapper()
{
}
}
This is initialised in the Application_Startup in App.xaml.cs
private void Application_Startup(object sender, StartupEventArgs e)
{
BootStrapper.Build();
this.RootVisual = new MainPage();
}
I have set the DataContext of one of my views to use my BootStrapper
DataContext="{Binding Path=FlexContractStructureViewModel,
Source={StaticResource classes:BootStrapper}}"
But I get the error Cannot find a Resource with the Name/Key classes:BootStrapper
The book I am using states to make a change to the App.xaml to add
But I cant do that because ObjectDataProvider is not recognised
I have tried the equivalent below with no luck
<bs:BootStrapper xmlns:bs="clr-namespace:SLDashboard2.Classes" x:Key="BootStrapper"/>
I think this may be related to having BootStrapper static? But I dont want to be constantly creating new Containers
Can someone help please?
Paul
Wrong. Shouldn't you be registering all your ViewModels in your IoC? and then you inject them to your constructors. They should never be static and I don't usually use static resources as my datacontext in my view

Broken binding with Prism, Silverlight and ViewFirst approach

The problem we are having is that we cannot get binding to work in our
prism silverlight application when using the view-model first
approach. The view first approach work fine. We have gone over the
official documentation and various web sites, but have still not
resolved the issue. Below is the code for both the view-model first,
and the view first approach. Are we missing something? Read about it on my blog http://silvercasts.blogspot.com
View-Model first approach:
Bootstrapper:
internal void RegisterLoginRegionAndView()
{
IRegionManager regionManager = Container.Resolve<IRegionManager>();
regionManager.RegisterViewWithRegion(ShellRegionNames.MainRegion,
() => Container.Resolve<IViewModel>().View);
}
ViewModel:
public ViewModel(IView view)
{
View = view;
View.SetModel(this);
User = new User();
User.Username = "TestUser";
}
ViewModel Interface:
public interface IViewModel
{
IView View { get; set; }
}
View Interface:
public interface IView
{
void SetModel(IViewModel model);
}
View Xaml:
<TextBox x:Name="Username" TextWrapping="Wrap" Text="{Binding User.Username}" />
View Code Behind:
public void SetModel(IViewModel viewModel)
{
this.DataContext = viewModel;
}
View first approach
Bootstrapper:
regionManager.RegisterViewWithRegion(ShellRegionNames.MainRegion, typeof(IView));
ViewModel:
public ViewModel()
{
User = new User();
User.Username = "TestUser";
}
View Code Behind:
public View(IViewModel viewModel)
{
InitializeComponent();
this.DataContext = viewModel;
}
Your implementation of SetModel on your view needs to be as follows:
public void MyUserControl : UserControl, IView
{
//...
public void SetModel(IViewModel vm)
{
this.DataContext = vm;
}
}
If that's not there, it needs to be (you haven't posted your implementation of SetModel, but this would be the source of the issue in this case).
If this is not the issue, it's likely because your ViewModel does not implement INotifyPropertyChanged. I usually use a base ViewModel that does this:
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And then all of my ViewModels derive from that:
public class MyViewModel : ViewModelBase
{
private User _user;
public User User
{
get { return _user; }
set
{
_user = value;
OnPropertyChanged("User");
}
}
}
Note: in your case the "User" object should probably also be a ViewModel and also raise OnPropertyChanged for the Username property.
Hope this helps.
The obvious difference to me is that you set the DataContext in the "view first" approach, but not in the "view model first" approach. I'm not sure if Prism sets the DataContext for you (I'd guess that you're assuming that it does) but try setting the DataContext manually to see if this is the problem. In your ViewModel constructor you call View.SetModel(this) - does that call set the DataContext?
The problem was that I was using the SetModel method before the data object was instanced. Moving it like this:
public ViewModel(IView view)
{
View = view;
User = new User();
User.Username = "TestUser";
View.SetModel(this);
}
solved the problem.

Resources