WPF/Prism : Views return System.Object - wpf

I am new to WPF and Prism, but I already learned that you have to register a View in Unity as an object:
Container.RegisterType<Object,MyView>("My.Assembly.MyView");
Still, when I use
var RelativeUriToMyView = new Uri("My.Assembly.MyView",UriKind.Relative);
RegionManager.RequestNavigate(RelativeUriToMyView, RegionName, CallbackResult);
the MyView displays as System.Object, and the CallbackResult contains no Error.
What am I missing? I'm happy to provide more information if needed.

You would want to look at the RegionNavigationContentLoader.cs in the PRISM source code; Here is the code that is loading the view for you.
protected virtual object CreateNewRegionItem(string candidateTargetContract)
{
object newRegionItem;
try
{
newRegionItem = this.serviceLocator.GetInstance<object>(candidateTargetContract);
}
catch (ActivationException e)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateNavigationTarget, candidateTargetContract),
e);
}
return newRegionItem;
}
There are several helper methods that take the URI, extract the query string, and create the 'name' used to lookup your view and cast it as an object.
Essentially, the name you are using to associate your concrete class as an object with Unity is the same one you'll need to use when you try to resolve the object with Unity. Here is some pesudocode to explain,
Container.RegisterType<object, ConcreteClass>(typeof(ConcreteClass).FullName);
Locator.GetInstance<object>(UriWithFullName)
If none of this helps, post the RelativeUriToMyView so I can see the contents.
Good luck.

The issue seemed to be caused by registering the view with its FullName (My.Assembly.MyView) instead of its Name (MyView).
Edit:
Changed the question to more accurately reflect the issue.

Related

How to tag viewmodels when registering for MVVM messages?

Using MVVM Light, it is easy to register for certain types of messages:
public MyViewModel()
{
Messaging.Messenger.Default.Register<MyObject>(this,
new Action<MyObject>((o) => DataMember = o));
}
Now, I have multiple document views in my software which implies showing/hiding views when toggling between them. When a view instance is hidden, I want its registered messages to be ignored. Similarly, when a view instance is shown, I want its registered messages to be handled. Hence, a message token per document is required:
public MyViewModel(String documentID)
{
Messaging.Messenger.Default.Register<MyObject>(this,
documentID,
new Action<MyObject>((o) => DataMember = o));
}
The problem is, I cannot figure out where in XAML/code to specify this token!
Sure, I can provide the documentID from the view...
public MyView()
{
InitializeComponent();
DataContext = new MyViewModel("1234");
}
... effectively giving me the same problem. Where would I specify this "1234" value? I read about x:Arguments Directive, hoping that it would let me specify constructor arguments in XAML, but it seems it's only supported in Loose XAML :(
I can think of a couple of solutions, like having a global variable, ActiveDocumentID, that would be used as token when instantiating the viewmodel. Is there a better solution?

Refreshing ViewModel's Entity Framework context

I'm using WPF, MVVM and Entity Framework in my current project.
To keep things simple, let's say I have a viewmodel for CRUD operations towards a list of materials (Solid woods).
My ViewModel's EF context (WTContext) is initialized through property injection, for instance:
SolidWoods_VM newView = new SolidWoods_VM();
newView.Context = new WTContext(SettingsManager.Instance.GetConnectionString());
This way I'm able to test this ViewModel:
SolidWoods_VM swVM = new SolidWoods_VM();
swVM.Context = new FakeWTContext();
Imagine that during a insert operation something goes wrong and the WTContext.SaveChanges() fails.
What is the best way to refresh the ViewModels context?
Create a new bool property in the viewmodel named ForTestingPurposes, and when the SaveChanges method fails:
try
{
Context.SaveChanges();
}
catch
{
if (!ForTestingPurposes)
{
Context = new WTContext(SettingsManager.Instance.GetConnectionString());
}
}
Send a message to the mainviewmodel for context reloading (through mediator pattern):
Mediator.Instance.NotifyColleagues<SolidWoods_VM>(MediatorMessages.NeedToUpdateMyContext, this);
(Yet, this way I'd still need the bool property)
3.A more elegant solution, without aditional properties, provided for you guys :)
Why not abstract the methods/properties you need on your data context onto an interface and then have an implementation of that that handles the exception.
//WARNING: written in SO window
public interface IDataSource
{
void SaveChanges();
//... and anything else you need ...
}
public class RealDataSource : IDataSource
{
private WTContext _context;
public void SaveChanges()
{
try { _context.SaveChanges(); }
catch
{
_context = new WTContext(/*...*/);
}
}
}
This way you can still implement a fake/mock data source but your view model class doesn't need to know anything about how the data is actually retrieved.
My opinion is that your best bet would be the message.
You need a way to indicate that the save went wrong, and it might not serve all consumers of the class to have the context regenerated. If you're binding to your VM in there, for example, resetting the context might have other UI consequences.

How to Pass an object when navigating to a new view in PRISM 4

I am working on a PRISM application where we drill down into the data (to get more details).
In my implementation I have a nested MVVM and when I navigate down the tree I would like to pass a model to a my newly created view.
As far as I know, currently PRISM allows to pass strings, but doesn't allow to pass objects. I would like to know what are the ways of overcoming this issue.
i usually use a service where i register the objects i want to be passed with a guid. these get stored in a hashtable and when navigating in prism i pass the guid as a parameter which can then be used to retrieve the object.
hope this makes sense to you!
I would use the OnNavigatedTo and OnNavigatedFrom methods to pass on the objects using the NavigationContext.
First derive the viewmodel from INavigationAware interface -
public class MyViewModel : INavigationAware
{ ...
You can then implement OnNavigatedFrom and set the object you want to pass as navigation context as follows -
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
SharedData data = new SharedData();
...
navigationContext.NavigationService.Region.Context = data;
}
and when you want to receive the data, add the following piece of code in the second view model -
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
if (navigationContext.NavigationService.Region.Context != null)
{
if (navigationContext.NavigationService.Region.Context is SharedData)
{
SharedData data = (SharedData)navigationContext.NavigationService.Region.Context;
...
}
}
}
ps. mark this as answer if this helps.
PRISM supports supplying parameters:
var para = new NavigationParameters { { "SearchResult", result } };
_regionManager.RequestNavigate(ShellRegions.DockedRight, typeof(UI.SearchResultView).FullName, OnNavigationCompleted, para);
and implement the INavigationAware interface on your View, ViewModel or both.
you can also find details here: https://msdn.microsoft.com/en-us/library/gg430861%28v=pandp.40%29.aspx

How to get can CanAddNew to be true for a collection returned by RIA Services

RIA Services is returning a list of Entities that won't allow me to add new items. Here are what I believe to be the pertinent details:
I'm using the released versions of Silverlight 4 and RIA Services 1.0 from mid-April of 2010.
I have a DomainService with a query method that returns List<ParentObject>.
ParentObject includes a property called "Children" that is defined as List<ChildObject>.
In the DomainService I have defined CRUD methods for ParentObject with appropriate attributes for the Query, Delete, Insert, and Update functions.
The ParentObject class has an Id property marked with the [Key] attribute. It also has the "Children" property marked with the attributes [Include], [Composition], and [Association("Parent_Child", "Id",
"ParentId")].
The ChildObject class has an Id marked with the [Key] attribute as well as a foreign key, "ParentId", that contains the Id of the parent.
On the client side, data is successfully returned and I assign the results of the query to a PagedCollectionView like this:
_pagedCollectionView = new PagedCollectionView(loadOperation.Entities);
When I try to add a new ParentObject to the PagedCollectionView like this:
ParentObject newParentObject = (ParentObject)_pagedCollectionView.AddNew();
I get the following error:
" 'Add New' is not allowed for this view."
On further investigation, I found that _pagedCollectionView.CanAddNew is "false" and cannot be changed because the property is read-only.
I need to be able to add and edit ParentObjects (with their related children, of course) to the PagedCollectionView. What do I need to do?
I was just playing around with a solution yesterday and feel pretty good about how it works. The reason you can't add is the source collection (op.Entities) is read-only. However, even if you could add to the collection, you'd still want to be adding to the EntitySet as well. I created a intermediate collection that takes care of both these things for me.
public class EntityList<T> : ObservableCollection<T> where T : Entity
{
private EntitySet<T> _entitySet;
public EntityList(IEnumerable<T> source, EntitySet<T> entitySet)
: base(source)
{
if (entitySet == null)
{
throw new ArgumentNullException("entitySet");
}
this._entitySet = entitySet;
}
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
if (!this._entitySet.Contains(item))
{
this._entitySet.Add(item);
}
}
protected override void RemoveItem(int index)
{
T item = this[index];
base.RemoveItem(index);
if (this._entitySet.Contains(item))
{
this._entitySet.Remove(item);
}
}
}
Then, I use it in code like this.
dataGrid.ItemsSource = new EntityList<Entity1>(op.Entities, context.Entity1s);
The only caveat is this collection does not actively update off the EntitySet. If you were binding to op.Entities, though, I assume that's what you'd expect.
[Edit]
A second caveat is this type is designed for binding. For full use of the available List operation (Clear, etc), you'd need to override a few of the other methods to write-though as well.
I'm planning to put together a post that explains this a little more in-depth, but for now, I hope this is enough.
Kyle
Here's a workaround which I am using:
Instead of using the AddNew, on your DomainContext you can retrieve an EntitySet<T> by saying Context.EntityNamePlural (ie: Context.Users = EntitySet<User> )
You can add a new entity to that EntitySet by calling Add() and then Context.SubmitChanges() to send it to the DB. To reflect the changes on the client you will need to Reload (Context.Load())
I just made this work about 15mins ago after having no luck with the PCV so I am sure it could be made to work better, but hopefully this will get you moving forward.
For my particular situation, I believe the best fit is this (Your Mileage May Vary):
Use a PagedCollectionView (PCV) as a wrapper around the context.EntityNamePlural (in my case, context.ParentObjects) which is an EntitySet. (Using loadOperation.Entities doesn't work for me because it is always read-only.)
_pagedCollectionView = new PagedCollectionView(context.ParentObjects);
Then bind to the PCV, but perform add/delete directly against the context.EntityNamePlural EntitySet. The PCV automatically syncs to the changes done to the underlying EntitySet so this approach means I don't need to worry about sync issues.
context.ParentObjects.Add();
(The reason for performing add/delete directly against the EntitySet instead of using the PCV is that PCV's implementation of IEditableCollectionView is incompatible with EntitySet causing IEditableCollectionView.CanAddNew to be "false" even though the underlying EntitySet supports this function.)
I think Kyle McClellan's approach (see his answer) may be preferred by some because it encapsulates the changes to the EntitySet, but I found that for my purposes it was unneccessary to add the ObservableCollection wrapper around loadOperation.Entities.
Many thanks to to Dallas Kinzel for his tips along the way!

How to filter Observable Collection Class Collection

I have implemented Linq-To-Sql..
Add necessary table in it...
after that linq class will automatically set property for field..
I implemented one class using ObservableCollection class.. and pass datacontextclass object in its constructor...
so after getting all data how to filter it?
public class BindBookIssueDetails : ObservableCollection
{
public BindBookIssueDetails(DataClasses1DataContext dataDC)
{
foreach (Resource_Allocation_View res in dataDC.Resource_Allocation_Views)
{
this.Add(res);
}
}
}
private BindBookIssueDetails bResource;
bResource = new BindBookIssueDetails(db);
_cmbResource.ItemSource=bResource;
Please Help me.
You can use CollectionViewSource and filter it. So that it affect only at the View(.XAML) side
ICollectionView collectionView = CollectionViewSource.GetDefaultView(bResource);
collectionView.Filter = new Predicate<object>(YourFilterFunction);
Check out this blog for more details. http://bea.stollnitz.com/blog/?p=31
I tried to use #Jobi's solution but for some reason I got an exception trying to fire FilterFunction.
So I used a slightly different approach. I cast CollectionViewSource's DefaultView to a BindingListCollectionView
myVS=(BindingListCollectionView)CollectionViewSource.GetDefaultView(sourceofdata);
and now I can construct an SQL-like filter string and apply it like that:
myVS.CustomFilter=myfilterstring;
I will still try to resolve my problem (I presume #Jobi's solution is more flexible).

Resources