I need someone to confirm what I am seeing before I may a change to the domain of the application because of this issue. The issue is that when databinding against interfaces that inherit from one another, you can not see the properties on the base interfaces.
I am working on a WinForms application that uses databinding. This is in .net3.5 and no I can not use wpf.
Anyways, I have a setup something like this.
public interface IClassOne
{
string Prop1 { get; set; }
}
public interface IClassTwo : IClassOne
{
string Prop2 { get; set; }
}
public abstract class ClassOne : IClassOne
{
public string Prop1 { get; set; }
}
public class ClassTwo : ClassOne, IClassTwo
{
public string Prop2 { get; set; }
}
The base class would hold common properties and logic. The base interface would have those common properties on it so they would have to be implemented on each concrete implementation.
If I was databinding to my class structure above, I would be binding to IClassTwo. The problem is when I databind to IClassTwo, I can not see Prop1 in any of the designer operations for WinForms. Even if I get around that limitation and get a control to be bound to Prop1, it does not work.
However if I bind two ClassTwo, then databinding works.
I do not want to deal with the concrete classes because that would make using mocks and testing too hard. I also do not want to put everything on IClassTwo because I would have to repeat code when I make another concrete implementation.
What I need to know is if this truly doesn't work. If you know why, that would be a bonus.
Thank you
Tony
http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/4151e6b6-44f7-45e2-9a8e-92c4f8539095/?prof=required
Here is a snippit of what is posted on MSDN as to why this doesn't work. The poster who wrote this goes by "franking".
No, it's not possible to bind to an interface! BindingSource offers some help to use a type as data source. Internally it will instantiate a BindingList<> instance using the type information. Also adding new items will work, but AddNew() will fail unless you subscribe the AddingNew event.
Related
I'm using the MVVM pattern in our WPF application to allow for comprehensive unit testing. The MVVM pattern itself is working great, however I'm struggling to adapt the pattern in a way that means I can use the design-time data support of WPF.
As I'm using Prism the ViewModel instances are generally injected into the constructor of the view, like so
public MyView(MyViewModel viewModel)
{
DataContext = viewModel;
}
Dependencies for the ViewModel are then injected into the constructor, like so
public class MyViewModel
{
public MyViewModel(IFoo foo, IBar bar)
{
// ...
}
// Gets and sets the model represented in the view
public MyModel { get; set; }
// Read-only properties that the view data binds to
public ICollectionView Rows { get; }
public string Title { get; }
// Read-write properties are databound to the UI and are used to control logic
public string Filter { get; set; }
}
This is generally working really well except when it comes to design data - I wanted to avoid compiling design-data specific classes into my released assembly and so I opted to use the {d:DesignData} approach instead of the {d:DesignInstance} approach, however in order for this to work correctly my ViewModel now needs to have a parameterless constructor. In addition, I also often need to change additional properties either to have setters or to be modifiable collections in order to be able to set these properties in XAML.
public class MyViewModel
{
public MyViewModel()
{
}
public MyViewModel(IFoo foo, IBar bar)
{
// ...
}
// Gets and sets the model represented in the view
public MyModel { get; set; }
// My read-only properties are no longer read-only
public ObservableCollection<Something> Rows { get; }
public string Title { get; set; }
public string Filter { get; set; }
}
This is worrying me:
I have a parameterless constructor that is never intended to be called and isn't unit tested
There are setters for properties that only the ViewModel itself should be calling
My ViewModel is now a jumbled mixture of properties that should be modified by the view, and those that shouldn't - this makes it tricky to tell at a glance which piece of code is responsible for maintaining any given property
Setting certain properties at design time (e.g. to see styling on the Filter text) can actually end up invoking ViewModel logic! (so my ViewModel also needs to be tollerant of otherwise mandatory dependencies being missing at design time)
Is there a better way to get design-time data in a WPF MVVM application in a way that doesn't compromise my ViewModel in this way?
Alternatively should I be building my ViewModel differently so that it has more simple properties with the logic separated out somewhere else.
First, I would recommend you to have a look at this video where Brian Lagunas provides several best practices about MVVM. Brian is - at least - involved in the development of Prism, as his name appears in the nuget packages information. Didn't check further.
On my side I only use bits of Prism, and my Model and ViewModel always offer blank constructors (like what Brian shows), the data context is assigned in the view's XAML, and I set the properties values like :
<MyView.DataContext>
<MyViewModel />
</MyView.DataContext>
and
public void BringSomethingNew()
{
var myView = new View();
(myView.DataContext as ViewModel).Model = myModel;
UseMyView();
}
Another benefit with this approach is that the ViewModel is created once, with the same path at design and run time, so you create less objects and save GC efforts. I find this elegant.
With regards to the setters, the design data will still work if you make them private, like:
public string MyProp { get; private set; }
Ok, customize it to manage NotifyPropertyChange at your convenience, but you've got the idea.
Now, I don't have yet a solution to manage ObesrvableCollections (I face the same problem, although putting multiple values in XAML sometimes work... ???), and yes, I agree that you have to manage the case when the properties are not set, like setting default values in the constructor.
I hope this helps.
I too have worked with NUnit testing with WPF and MVVM implementation. However, my version is reversed from yours. You are creating the view first, then creating the model to control it.
In my version, I create the MVVM model FIRST and can unit test it till the cows come home and not worry about any visual design... if the model is broken, so too will the visual implementation.
in my MVVM model, I have a method to "GetTheViewWindow". So, when I derive from my MVVM baseline, each view model has its own view its responsible for. So via a virtual method, each instance will do its own new view window when being applied for production.
public class MyMVVMBase
{
private MyViewBaseline currentView;
public MyMVVMBase()
{ // no parameters required }
public virtual void GetTheViewWindow()
{ throw new exception( "You need to define the window to get"; ) }
}
public class MyXYZInstanceModel : MyMVVMBase
{
public override void GetTheViewWindow()
{
currentView = new YourActualViewWindow();
}
}
Hope this helps as an alternative to what you are running into.
My WPF application follows the MVVM pattern. There are three views:
MainWindow
LoginView
ProjectsView
LoginView and ProjectsView are user controls imported by the MainWindow. Both views have their view model assigned. LoginViewModel defines a property ProjectList which is set by calling a webservice. Now LoginViewModel needs access to the ProjectList property and others.
I am aware that one solution might be a redesign so that there is only one view and one view model. I would do that as a backup solution but I would favor not to do so.
How should this be done? Should I use some kind of EventAggregator like in Prism? Or are there other ways to do this?
So if i understood clearly, ProjectList property should be accessed from both 'LoginViewModel' and 'ProjectsViewModel'. I'd try to implement it in the 'MainViewModel' so child viewmodels can access it in a natural way.
An IEventAggregator is like a box in which you can add events, or find and subscribe to one, so i would say it's not what you need.
Anyway, you could register your custom interface (box type) in the UnitySingleton.Container, which would expose ProjectList for it to be accessible everywhere. This approach makes a lot of sense when modules, which are separate assemblies, need to communicate whith each other.
If this is overkill or not in your case is something you should decide, i'd personally go with the 'put it in the mainviewmodel' option.
-- Sample -- (not tested)
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
LoginVM = new LoginViewModel(this);
ProjectsVM = new ProjectsViewModel(this);
RetrieveProjectList();
}
public LoginViewModel LoginVM { get; private set; }
public ProjectsViewModel ProjectsVM { get; private set; }
public object ProjectList { get; private set; }
private void RetrieveProjectList()
{
ProjectList = ....
}
}
It's pretty simple as you see, LoginVM and ProjectsVM will hold a reference to the MainViewModel that created them, therefore giving them access to ProjectList.
How should this be done? Should I use some kind of EventAggregator
like in Prism? Or are there other ways to do this?
Here are a few ideas:
You can create a view-model class that both view-models
inherit from. This base class will contain the shared properties.
Create a static class that contains the shared properties.
Using dependency injection, create a class that contains the
properties, register it as a singleton in your container and inject
it into your view-model's ctors.
Also, I believe that the EventAggregator is best suited for communicating between modules/assemblies. In your example, it seems like everything is in the same assembly.
I am working on an app where I am trying to use MVVM for the first time. After reading some things, I think I might have misunderstood what goes in the Model.
All my app does right now is make a request to get some data, display it, allow the user to edit it, and save it if changes were made.
Here is an example of my current setup. I read some Employee data, which returns groups of employees ("Managers", "VPs", etc.). Each group contains a list of people. I created an interface to represent the groups:
public interface IEmployeeGroup : INotifyPropertyChanged
{
bool IsDirty { get; set; }
string GroupName { get; set; }
ObservableCollection<IPerson> People { get; set; }
}
public interface IPerson : INotifyPropertyChanged
{
bool IsDirty { get; set; }
string PersonName { get; set; }
int Id { get; set; }
}
I then create concrete EmployeeGroup and Person classes implementing those interfaces. And thats all they do, expose the specified properties.
That is all I have for my model.
My view model implements the below interface:
public interface IEmployeeGroupsViewModel
{
ICommand AddEntryCommand { get; }
ICommand SaveCommand { get; }
ObservableCollection<IEmployeeGroup> EmployeeGroups { get; set; }
ObservableCollection<IPerson> People { get; set; }
}
The view model makes the call to get the actual data, creates the EmployeeGroup and Person objects, and then returns them in properties for the view to bind to. When the user wants to save his changes, the view model makes the call to persist the changes.
Am I putting too much in my view model, which should be in the model instead? Right now my model does nothing, they are just the classes that represent the objects.
If I am off track here, can someone give me some advice? How would I change my above scenario for example?
Thank you.
There's nothing wrong with your approach. You are free to either expose mapped model properties from your view model if they require formatting, or you can expose your model directly from your view model if no changes need to be made.
MVVM is about testability, not pattern purity. As long as what you are doing works, you can always refactor later.
That looks right to me.
I could be wrong, but I don't really see a benefit from making your view model interfaces derive from INotifyPropertyChanged. That seems like unnecessarily coupling together two things that don't really have any intrinsic relationship to one another. I'd just declare the PersonViewModel class (for instance) as:
public class PersonViewModel : IPerson, INotifyPropertyChanged
I am currently working on a new project of mine that is going to be a data record visualizer (for records in Pascal). It should provide a way to define a given record with data fields and pointer fields and then there will be an example view where you can see the record "in action".
Now the problem I am having is that in this model there are records and components and the relationship between them is that one record has multiple components (data and pointer as mentioned above).
I want to use MVVM for the app but I am now unsure how I should approach this. I modelled the record and components into RecordViewModel and ComponentViewModel (with derivates DataComponentVM, PointerComponentVM).
Now to provide a look for these VMs there are 2 options as far as I know:
Deriving the ViewModels from Control and providing a ControlTemplate
Creating a UserControl using the ViewModel as DataContext
The UserControl approach works fine for the RecordViewModel but when I try to design the way the ComponentViewModels are shown (in a ContentPresenter) this approach fails because I would need to provide a collection of UserControls (instead of DataComponentViewModels) in my RecordViewModel that would make that work (and I am pretty sure that is not a good idea).
The Control approach also has the problem that the ViewModels aren't POCOs anymore which I think has a strange feel to it and is also not considered good practice.
Is there any other way to solve the problem? Do you have any other good advice for me in this regard?
Thanks in advance!
Code:
public class RecordViewModel : BaseViewModel
{
public RecordViewModel()
{
Components = new ObservableCollection<ComponentViewModel>();
}
public ObservableCollection<ComponentViewModel> Components { get; set; }
}
public class DataComponentViewModel : ComponentViewModel
{
public string Type { get; set; }
}
public class PointerComponentViewModel : ComponentViewModel
{
public object Target { get; set; }
}
Oh god why didn't I think of this before?
I was only thinking about ControlTemplates (therefore needing my ViewModels to derive from Control) when there are also DataTemplates that work exactly like I wanted them to.
I got lost as to why you think you need to provide a collection of user controls, but it sounds like what you really want is for the RecordViewModel to have some variation of:
ObservableCollection<ComponentViewModel> Components
Components is then bound in xaml to the ItemsSource property of some sort of ItemsControl. Whether or not the ComponentViewModel needs it's own UserControl depends on what you are trying to do with it.
If that doesn't start to click for you then you may want to post some code so we can sort it out.
I'm currently working on what will be my first real foray into using MVVM and have been reading various articles on how best to implement it.
My current thoughts are to use my data models effectively as data transfer objects, make them serializable and have them exist on both the client and server sides.
It seems like a logical step given that both object types are really just collections of property getters and setters and another layer in between seems like complete overkill.
Obviously there would be issues with INotifyPropertyChanged not working correctly on the server side as there is no ViewModel to which to communicate, but as long as we are careful about constructing our proper domain model objects from data models in the service layer and not dealing the the data models on the server side I don't think it should be a big issue.
I haven't found too much info about this approach in my reading, so I would like to know if this is a pretty standard thing, is this just assumed to be the de facto way of doing MVVM in a multi-tier environment?
If I've got completely the wrong idea about things then thoughts on other approaches would be appreciated too.
You can use whatever model you feel comfortable with, yes all of your properties will need INotifyPropertyChanged behavior. How this will effect the service layer is entirely down to your implementation.
I'm assuming that you ment that you bind to your DTO's in your view?
How I see it is that there is an impedence mismatch between the layers of the application, that is your
Domain Model probably looks simliar to your Relational Model, with subtle but crucial differences. There is also
a mismatch between the Domain Model and your DTO's (objects may be flattened, computed properties, etc, ...). It's tempting to bind directly to the DTO's as they are probably designed to have what you need for the particular operation, however there is also an impedence mismatch between the DTO and what is needed by the view in order to acheive the desiged outcome. This is where the View Model comes in. The view model has responsibility to proxying the DTO properties to the view, it is responsible for letting the view know if there are validation errors, and routes commands to the appropriate handler (Save, Delete, etc, ...).
I tend to set things up in the following way :
// POCO object. Serializable.
public class AddressDto
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
// IDataErrorInfo for validation.
public class AddressViewModel : INotifyPropertyChanged, IDataErrorInfo
{
private readonly AddressDto addressDto;
public AddressViewModel(AddressDto addressDto)
{
this.addressDto = addressDto;
}
public int Id { /* get and set for property changed event and update dto */ }
public string Street { /* get and set for property changed event and update dto */ }
public string City { /* get and set for property changed event and update dto */ }
public string Country { /* get and set for property changed event and update dto */ }
...
// IDataErrorInfo implementation
}
public class EditAddressViewModel : INotifyPropertyChanged
{
public AddressViewModel Address { /* get and set for property changed event */ }
public ICommand Save { /* setup command */ }
public ICommand Cancel { /* setup command */ }
private void Save()
{
}
private void Cancel()
{
}
}
Your EditAddressView would then bind to the EditAddressViewModel. Basically the rule is all of your UI behavior should be expressed in terms of your view model.
Yes that does mean extra work, howerver there are things you can do to simplify things a bit (code generation etc). I'm actually working on a library that aims to simplify whole MVVM process using a fluent api. Check it out at http://fluentviewmodel.codeplex.com/
I'm no expert on this. I had just the same scenario. I agree with you that that is quite an overkill. I've been using this solution for quite some time now and haven't encountered any issues. The INotifyPropertyChanged isn't a big problem for me since nothing on the server-side will subscribe to the PropertyChanged event. If you will use inheritance on your data models, then all must be serializable. In my scenario, I have two base classes for my data models: one that is used for data transfer, and the other not.
I decided to have a property "Model" on my ViewModel. In the model itself I already implement IPropertyNotifyChanged and IDataErrorInfo. In my ViewModel I thus skip properties where the code would simply "fall-through" to the model. Instead, the View binds directly to the model for those properties.
For more complicated cases, where I have to adjust the data in the model to fit the view, I do this in the ViewModel. Also, the commands, etc. are in the ViewModel. But I do not see the reason to have boilerplate code in the ViewModel repeating the same stuff which I already have in the model.