Xaml - add existing control to grid - wpf

Trying to develop using MVVM:
I have this Csla.PropertyStatus control that is created in my ViewModel.
I want to add it in the xaml (via binding, i think) and set some additional properties there (such as the target).
I don't know how i could do that, not even if that is possible.
I was looking for something like
<csla:PropertyStatus Instance="{Binding Path=MyStatus}"
Target="{Binding ElementName=txtTextBox}"
Grid.Column="2" Grid.Row="0"/>
Is that possible somehow?... i NEED to create it in the ViewModel because i need to set some property that the view (XAML) is not allowed to know about.
Edit:
The property i'm talking about is the model. The PropertyStatus needs a reference to the business object to perform the validation.
But considering the paradigm of MVVM (or as i understand it), the view should be decoupled from the model, and should only know about the ViewModel. I might change that approach, though...

You CAN'T do this. BTW, the view is all about UI controls and their properties, so saying the view is not allowed to "know about" a property on one of its elements is a bit... extreme. A description of what you are trying to accomplish here might help in providing you with a decent answer.

Related

How to use MediaElement.NaturalDuration to set MediaTimeline.Duration in WPF MVVM

My MVVM program is a media player and uses the Media Element's Natural Duration property to set the Media Timeline's duration. Before I implemented MVVM design pattern, I could simply put
MyMediaTimeline.Duration = MyMediaElement.NaturalDuration;
in the code-behind. I am new to using MVVM but I believe this is not the correct way to perform this action according to the MVVM design pattern. I believe that MediaElement.NaturalDuration is not a dependency property so it cannot be bound to directly. Do I need to make it a dependency property somehow? Would this be coded in the ViewModel?
When we need to implement functionality like this that relates to UI controls using MVVM, we have a few options. One is to implement some kind of service or manager class that can implement this functionality for us and another is to use Attached Properties. Out of these two options, I believe this second option to be more suitable for this problem.
However, there is absolutely nothing wrong with adding event handlers into the code behind of your view, even when using MVVM. I keep seeing new users panicking over what to do rather than use the code behind when using MVVM. This is a common misconception about MVVM.
If you really know how to use Attached Properties properly, then I would advise that you use one (or more) of those to solve your problem, otherwise I would happily advise you to use the code behind. Note that if your view models are correctly data bound to your views, then you can access your view model from the code behind like this:
TypeOfViewModel viewModel = (TypeOfViewModel)DataContext;

Pattern for using dependency property for non simple type on a WPF user control

I am a newbie to WPF, and am trying to learn the standard idioms. I have a user control that allows the user to enter a mailing address, composed of six text boxes. I have also defined an interface IMailAddress, and a concrete class MailAddress that is a set of properties for the standard mail address fields. (US only for the moment.)
I figure by having an interface it means I could have some database class that holds everything about a person but implements this interface for the specific needs of this control.
What is the idiomatic way to tie this type into the control? I can certainly implement it as a dependency property, but does that make any sense with a type like this? Would I be better making it a standard property, and then raising a routed event when the value changed?
I'm not so much concerned about this specific example, but more generally what is considered best practice for these types of scenario.
Having your user control expose an IMailAddress property as a dependency property is perfectly valid. WPF itself does similar things; for example, ItemsControl expects you to bind a collection to it, so it exposes an ItemsSource dependency property of type IEnumerable.
User controls/custom controls are a good way to represent views, and don't let the MVVM freakazoids tell you otherwise :) Besides, there's no reason this can't work perfectly fine with MVVM - for example:
<local:MailAddressEditor
MailAddress="{Binding Path=Customer.BillingAddress}"
/>
One thing you may like to look at, though, is using a Custom Control instead of a UserControl. This will allow you to build a 'lookless' control that focuses on the logic behind editing an address, and allow users of your control to create Styles independently for rendering the control. When people use your control, they might use:
<local:MailAddressEditor
MailAddress="{Binding Path=Customer.BillingAddress}"
Style="{StaticResource SimpleInlineAddressEditor}"
/>
<local:MailAddressEditor
MailAddress="{Binding Path=Customer.BillingAddress}"
Style="{StaticResource ComplicatedAddressEditorWithGoogleMapsSelector}"
/>
In this case, we have one control, with two styles (and probably two ControlTemplates) to give the fields a different layout.
Custom controls are a great asset to a WPF developer - not everything has to be done via MVVM. Just try to stay conscious of the kind of code going into your custom control - if it's getting a little too logic-y, you might want to move some of that into a view model.
DependencyProperties are sort of fading away as INotifyPropertChanged is taking over with MVVM patterns. You should look at MVVM toolkits if you want to start using proper separation between your interface, data access, and business logic. You can still use DependencyProperties, but I would recommend you build a ViewModel to implement your interactions with your user control. One of the goals of MVVM is making testability easier by providing a ViewModel that can be verifed with unit tests outside of XAML-land.
A great starter MVVM toolkit for WPF is MVVM Light. A heavier weight MVVM toolkit would be Prism.

Matching implementations to parts of the pattern

While trying to understand the MVVM pattern I came across this video linked from the MVVM Light Toolkit website.
In TechDays 2010 - Laurent Bugnion states the WPF/Silverlight both use MVVM pattern for their structure. Can someone please clarify which components in WPF/SL (which Bugnion named specifically and are listed below) are the Model, ViewModel, and View?
These are the three items he stated as being a part of the MVVM pattern:
Code
Dependency Properties
Control Templates (Data Templates?)
I am the first to admit that this is a little bit stretched ;) but let me clarify. The statement was made to illustrate that MVVM is a very natural pattern in SL/WPF (and all other frameworks that use XAML and databinding). In the example, I was talking about the separation of concerns between the control's code (not referring to "code" in general, but specifically to a control's code, for example a Button class) and its template. In this illustration, the code acts like a ViewModel, i.e. it drives the view. The template is more obviously the View. And the glue between those is the databinding which is enabled through Dependency Properties.
When I say it is a bit of a stretch, we can see that there is no Model in this analogy. Also, the mechanism binding a control's view to its viewmodel (code) is a little more complex than just DPs and bindings. There are also naming conventions added to that.
In retrospect, I guess I could have been clearer, and I pushed this analogy a bit too far. I guess the main point I would like you to take from this is: In SL/WPF, code and view are loosely coupled through databinding. This is true for basic controls, and you can also structure your application in a loosely coupled manner, with the help of databindings.
I hope it makes a little more sense now ;)
Cheers,
Laurent
I haven't watched the video. Definitely the control templates and data templates are your views. The dependency properties are really also part of your view, but can be bound to data in a class which serves as a model for the view, i.e. the view-model. The "code" he's referring to must be the business logic which is your model.
I would think of it as three objects. You have a view object, like a TextBox control which has styling applied to it in the form of other view objects that comprise the templates. The TextBox also has dependency properties which are objects that can bind (synchronize) a value on the TextBox to a value on another object. That object is the DataContext of the TextBox, which is your view-model object. The view-model object can be thought of as an adapter for a model to support the specific needs of the view.
The Model represents the data and business logic. It should represent your business
(domain) and it should not be aware by anyway of your UI.
The View this is the UI – the bridge between your software and its users. Normally
the View is only aware of the ViewModel but there might be cases in which it may make
sense to expose the Model directly to it. So your XAML for UI like Grid, Button,
DataTemplate,Style, control Template etc can be found here.
The ViewModel: this is the way you connect your model to a specific View. See it has
code that massages your Models in a way that the View can consume. The ViewModel should be
View agnostic as the Model should. So the communication between View and ViewModel is
purely based on DataBinding. When you are dealing with MVVM pattern the use Dependency
property will be bare minimum. for example when you are creating any Custom control at
that time you have to use the Dependency property for the supporting the binding.
three items he stated as being a part of the MVVM pattern
There is a flaw in this. These things are not parts of MVVM; they enable MVVM. Parts of MVVM are Model, View and ViewModel. To call 'code' a part of MVVM or to call it a part of the ViewModel is oversimplifying and useless.
There is code in the Listbox control; it wouldn't function if there weren't.
Of course, code in the View is frowned upon while others say it is very well possible.
When trying to understand MVVM focus on the responsibilities of the Model, ViewModel and View and do not worry too much about code, dependency properties and Control Templates. You cannot map these to MVVM.

Where should I set the DataContext - code behind or xaml?

(honestly I searched and read all the 'related questions' that seemed relevant - i do hope i didn't "miss" this question from elsewhere but here goes...)
There are two different ways (at least) to set the DataContext. One can use XAML or one can use the code behind.
What is the 'best practice' and why?
I tend to favor setting it in XAML because it allows a designer to define collections on their own but I need 'ammunition' on why it's a best practice or why I'm crazy and the code behind is the bomb...
A third way you might look at is using a locator service. I usually have one class that is responsible for the creation of all my DataContext(VM's in most cases for me) and I create an instance of that class in the App.xaml Resources. Then I bind the DataContext in the XAML of each individual page.
i.e.
<Page DataContext="{Binding ViewModel,Source={StaticResource Locator}}" >
I think it depends on what you are setting the DataContext to, and ultimately personal preference.
I personally always do it in the code behind of my views because I find it overall cleaner, and it was how I was taught MVVM. Another thing to keep in mind is, there are times you may need to change your datacontext depending on what you are working with. If this is the case it's much cleaner/easier to do in the code behind rather than in XAML.
As you can see by the answers so far opinion is divided. In truth there is no best practice (I do get bee in my bonet about discusions of "best practice" in the Silverlight world, its way too young for best practice to be truely known.)
The reality actually is that you can't set the "data context" in Xaml. Unless you actually construct an object instance like this:-
<UserControl>
<UserControl.DataContext>
<local:MyDataProviderThing />
Ultimately something external has to assign either the DataContext property directly or indirectly via another property or via binding (as in Stephan's answer). Its this external context which is dictates whether it makes sense to do it in Xaml or not. Many MVVM solutions use a binding in Xaml, in some cases simply to avoid there having to be any code at all in code-behind rather than it truely being "better". Others set up the DataContext in code using a base class that your control derives from.
DataContext of the user control/view I assume? One advantage of setting data context in the code behind is the availability of dependency injection. Your DI container can take care of any dependencies for you dynamically at run-time.
With this pattern, I frequently set a view's Blend design DataContext in xaml using d:DataContext. The "design version" can provide mock data for use in Blend, while the true implementation is resolved at run-time.

Should your ViewModel expose XAML elements as properties or not?

Over at the StackOverflow question How can WPF Converters be used in an MVVM pattern? I've learned that Value Converters should not be used in the MVVM pattern since the functionality of a Value Converter should be handled by the ViewModel itself.
This makes sense.
But I remember reading that you should not expose XAML elements to the View, but instead expose only collections of data which the View then binds and displays using DataTemplates.
However, converters seem quite powerful (e.g. as they are used in the MVVM Template demo, see the "Messenger Sample" after unpacking it) in that they can convert objects to objects, e.g. Message objects to FlowDocument objects, or Customer objects into Visibility objects, or custom Status objects into Images, etc.
So if a ViewModel is going to take on the functionality of a Value Converter, it is going to have to expose XAML elements and properties such as StackPanel, Visibility, Color, FlowDocument, etc., right?
Does anyone see any reason why a ViewModel should not expose these rich XAML objects as Value Converters do?
Because then that limits the ViewModel to be used only with a specific visual representation.
Once you have the ViewModel emitting XAML, it puts design content into a developer's domain.
This means that the designer using Expression Blend cannot edit design assets - and the designer/developer workflow is broken.
Keeping the XAML on the page and using Value converters with data templating keeps the design separated from the code.
When your ViewModel exposes specific XAML it also limits that ViewModel to be used only in that specific instance and makes it less reusable.
Don't forget that you can use DataTemplates too. I can see some sense in keeping ValueConverters out of MVVM, but DataTemplates are all about transforming objects into GUI.
Your ViewModel can expose other objects (e.g. nested ViewModels) to the GUI, and the GUI can use <DataTemplate DataType="{x:Type SubViewModel}">... to map those objects to GUI.
Does anyone see any reason why a ViewModel should not expose these rich XAML objects as Value Converters do?
Absolutely, because it undermines all the goals of MVVM:
You're no longer unit testable, at least not easily.
You no longer have separation between logic (view model) and presentation (view). Thus, designers and developers cannot easily collaborate.
Code maintenance is more difficult because you've mixed the concerns together.
If I saw a view model returning a view, I wouldn't even classify it as MVVM.
I think one idea of mvvm/mvc/mvp etc. is to isolate the GUI code to one file/class.
If you do this can you change to some other UI without rewriting the other objects?
I think if you're passing around WPF specific objects the answer is no.
It's a value judgment you'll have to make for your self.
There is no absolute 100% rule that works for this or many other concepts when you discuss them without the perspective of why the community's mind has shifted as it has in this direction. There is no 'assumed' truth or science in 'conventional wisdom' regardless of how new or compelling it is at the time.
In other words - just do the best with your team as if your good, your already getting pulled down far more in human concerns than anything as real as this.

Resources