I am converting a C# WPF app to MVVM pattern and have couple questions:
I have a ViewModel tied to a Model with constructor requiring parameter that is result of selecting a single object from a JSON list returned to a search query. I suppose this means I cannot instantiate this ViewModel until search is performed.
This was not an issue previously as I didn't need to have a View databound to a ViewModel, and only collected text values from GUI to instantiate the object (Model) when all data is in place and I am ready to do something with it.
With MVVM, this is an issue, since I don't want to force this search to be the first user operation--the user should be able to modify any field in the GUI that is bound to the ViewModel.
What are some practical way of handling this type of situation? Seems I must either: a) wait for a search result to be selected before instantiating the VM or b) remove the parameter from the constructor and instead create a method that would be invoked on the instantiated VM for calculating/setting the properties that would otherwise be set by the constructor.
Second question: how can I implement the Search functionality--that is, how do I stage the List of results after search button is clicked? Previously I would deserialize the list in the SearchButton_Click method, and set the binding of a combobox to the resulting collection. With MVVM, I am having trouble picturing the state between return of result list and selection of the individual result. Do I create a separate ViewModel containing an empty list of target type bound to a combobox and a SearchTerm property bound to the Search TextBox and populate the combobox from the SearchButton Command ICommand? How do I then bind the selected item to my original viewmodel?
ViewModel:
class ObjectViewModel
{
public CustomObject data;
public ICommand Search;
public ObjectViewModel()
{
this.data = new CustomObject();
}
}
Model:
[DataContract]
public class User
{
[DataMember(Name = "EmailAddress")]
public string EmailAddress { get; set; }
[DataMember(Name = "FirstName")]
public string FirstName { get; set; }
[DataMember(Name = "FullName")]
public string FullName { get; set; }
...
}
[DataContract]
public class CustomObject
{
public User Owner;
...
}
View (not yet rewritten):
<TextBox Margin="5,0" Name="Owner"></TextBox>
<Button Name="Search" Content="Lookup" Click="OwnerLookUp_Click"></Button>
<ComboBox Name="OwnerMatches" SelectionChanged="OwnerMatches_SelectionChanged" Visibility="Hidden"/>
OwnerLookUp_Click takes text from Owner textbox and returns ObservableCollection and binds it to OwnerMatches. OwnerMatches_SelectionChanged sets Owner textbox to the selected item's Fullname property.
In this scenario, what am I going to bind to data.Owner in the ObjectViewModel?