Using DataAnnotations for validation in MVVM - silverlight

I've discovered the new data annotation features of SL3 and I'm using them for user input validation.
I've got inputs like these:
<dataInput:Label Target="{Binding ElementName=inputName}"/>
<TextBox
x:Name="inputName"
Text="{Binding RequestDemoData.Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}"/>
<dataInput:DescriptionViewer {Binding ElementName=inputName}"/>
and my model looks like that:
[Display(ResourceType = typeof(Resources.Resources), Name = "Name", Description = "NameDescription")]
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "NameRequired")]
[RegularExpression(#"^[^0-9]*[a-zA-Z]+[^0-9]*$", ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "NameError")]
public string Name
{
get
{
ValidateProperty("Name", _name);
return _name;
}
set
{
if (_name != value)
{
ValidateProperty("Name", value);
_name = value;
OnPropertyChanged("Name");
}
}
}
So far, so good. If the user inputs some wrong data, I get an error message when he/she focuses out. The issue is that I've got a submit button bound to an ICommand and I can't work out how to make the error message appear when the user clicks it.
The bad way is to add some code-behind and do GetBindingExpression(foo).UpdateSource() and that would sort it out. The downside is that it's completely unmanageable and I hate to habe code-behind on my viewa.
http://www.thejoyofcode.com/Silverlight_Validation_and_MVVM_Part_II.aspx proposed a solution and I'm going to follow it but I'd like to know if there isn't an easier way.
Cheers.

Unfortunately, there is not much of a better way to do this. The only way to have the UI update itself based on validators is in the setter of the binding.
This, I believe, is a huge limitation of the validation system in Silverlight. That JoyOfCode article is really the best way to go about it.
I would also recommend the article by the same publisher where you can bind errors to your viewmodel, but it doesn't work the other way around.

I have also used Josh's approach on a very large scale LOB application and whilst it is messy it does work. The Validation Context in particular is likely to get you out of a few scraps with more complex logic.

Related

Is there a way to refer to a binding in the code behind

I'm using the Actipro ribbon in my application and making use of the way that one can integrate a document title with the main ribbon title when a standard mdi host is being used (the docking is also Actipro docking). Now whilst I'm using a specific vendor's controls I think / hope that my question is a little more generic.
Currently the Xaml that is providing this functionality is marked up like this.
<ribbon:RibbonWindow.DocumentName>
<MultiBinding Converter="{StaticResource ConditionalConverter}">
<Binding ElementName="window" Path="IsMDIChildMaximized" />
<Binding ElementName="standardMdiHost" Path="PrimaryWindow.Title" />
<Binding Source="{x:Null}" />
</MultiBinding>
</ribbon:RibbonWindow.DocumentName>
The ribbon itself is named so in the code behind I can write something along the lines of;
MainRibbonWindow.DocumentName
However I can't get as far as the MultiBinding. Very specifically I would like to find a way to dynamically set ElementName on the second line of the binding in the xaml
<Binding ElementName="standardMdiHost" Path="PrimaryWindow.Title" />
because I know that the actual standardmdihost that is being refered to will change (everything else will remain the same).
The whole area of binding in wpf is still proving to be a very sharp learning curve, so I'd welcome any suggestions as to how I might go about achieving the desired result, or even if it's possible to do so in the first place.
I have come across this post, but I'm not sure if it really is the answer and even if it is how I would set about implementing it in this situation.
Many thanks
EDIT
Realised that I could probably do this in code by setting bindings along this sort of line:
Dim binding As New MultiBinding() With {.Converter = New BooleanAndConverter()}
binding.Bindings.Add(New Binding("AreWindowsMaximized") With {.Source = host})
binding.Bindings.Add(New Binding("HasItems") With {.Source = host})
Me.SetBinding(IsMDIChildMaximizedProperty, binding)
However preliminary attempts
Dim binding2 As New MultiBinding() With {.Converter = New ConditionalConverter()}
binding2.Bindings.Add(New Binding("Binding1") with {.ElementName = "MainRibbonWindow", .Path = IsMDIChildMaximized}
are not going quite as expected. If anyone could hazard a guess at what might work I'd be very grateful.
You'd have much more luck by data binding the DocumentName property to a property in your view model. That way, you are free to generate the value in code... perhaps something like this:
In XAML:
<ribbon:RibbonWindow DocumentName="{Binding DocumentName, Mode=OneWay}" ... />
In code:
public string DocumentName
{
get { return string.Format("{0}{1}", Value1, Value2); }
}
private string Value1
{
get { return value1; }
set { value1 = value; NotifyPropertyChanged("DocumentName");
}
private string Value2
{
get { return value2; }
set { value2 = value; NotifyPropertyChanged("DocumentName");
}
Then you just need to set Value1 and Value2 to whatever values you need and they will update the DocumentName using the INotifyPropertyChanged interface (or more accurately, the INotifyPropertyChanged interface will notify the UI of a change in the DocumentName property and then retrieve the latest value).
Just in case anyone should stumble across this and have a similar issue. My original mistake was in failing to properly understand how the bindings syntax worked and that all the clues needed to do this successfully were already in the xaml that I was looking to remove and replace wit code.
The end result (which does work) turned out to be;
Dim binding2 As New MultiBinding() With {.Converter = New ConditionalConverter()}
binding2.Bindings.Add(New Binding("IsMDIChildMaximized") With {.Source = MainRibbonWindow})
binding2.Bindings.Add(New Binding("PrimaryWindow.Title") With {.Source = host})
SetBinding(DocumentNameProperty, binding2)
This was a very specific issue involving the Actipro ribbon and docking ommands and the two sources (MainRibbonWindow and host) are the main window whose title we are trying to integrate with that of the document window, and the standardMdiHost itself.
I'd just like to take this opportunity to express my thanks both to those of you who read this question and posted suggestions and to Actipro themselves who pointed out the error of my ways and provided the final correct code that worked.

Updating a DateTime to a Label in WPF

I am fairly new to WPF so am not really sure what I am doing wrong here. I want to the current time (Datetime.Now) to be displayed and updated to a label on a window. The time would be called to update in a method that loads data from a database (like a "last updated" idea). This methoud is called every 2 minutes (kept by a timer on a thread) once the user is logged in. I have the following class for the time object...
public class UpdatingTime : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private DateTime _now;
public UpdatingTime()
{
_now = DateTime.Now;
}
public DateTime Now
{
get { return _now; }
private set
{
_now = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Now"));
}
}
}
public void Update()
{
Now = DateTime.Now;
}
}
In the window's class constructor, I have...
UpdatingTime updateTime = new UpdatingTime();
lastUpdate.DataContext = updateTime;
In the method that loads the data from the database, I call the Update() method by...
updateTime.Update();
I think my data binding is the problem though (like I said, I'm pretty new). My label in the xaml file looks like...
<Label Name="lastUpdate" Margin="10" Height="auto" Content="{Binding Source updateTime, Path=Now}"
Visibility="Hidden" FontSize="20" />
The reason that visibility is hidden is because I set it to Visible once the user is logged in, I've tested that and I'm sure its not the issue. To be clear, the backend code is in the code behind file to the corresponding xaml file (eg Window.xaml, Window.xaml.cs), so I do not think I am missing a reference either.
The problem is that when I run the application, nothing at all displays (it compiles, and no exceptions are thrown). I am not sure what I am doing wrong, if anyone could shed some light on this I would greatly appreciate.
Also, if you could mention some good resources to learning and becoming familiar with WPF that you found helpful, that would be awesome. I am not sure what the DataContext really is and if I am using it correctly also.
Thanks.
Your Binding statement for the Content has a syntax error, and it is wrong.
should be:
Content="{Binding Now}"
or (identical):
Content="{Binding Path=Now}"
No need for 'Source' (and if you have multiple properties in Binding - you must have a comma).
For WPF resources, search in this site for [wpf] - the question with the most votes is a summary of resources: MVVM: Tutorial from start to finish?

StatusBar not always updating

I am relatively new to MVVM, and I am trying to code up a basic Status Bar for an MVVM WPF application. I think I have the gist of things, but for some reason, the status bar does not always update, and I am not sure why.
In my ViewModel, I have a basic property that I update when I change a status message:
public string StatusMessage
{
get { return _statusMessage; }
set
{
if (value == _statusMessage) return;
_statusMessage = value;
base.OnPropertyChanged(() => this.StatusMessage);
}
}
My OnPropertyChanged method (which I have in a base ViewModel class that implements INotifyPropertyChanged) looks like so (got this idea from Gunther Foidl; wish I could claim credit for it because I think it's slick but I'm not quite that smart):
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> exp)
{
MemberExpression me = exp.Body as MemberExpression;
string propName = me.Member.Name;
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
At any rate, this all works great for all of my controls except one. On my MainWindow.xaml file, I have a StatusBarItem control bound to the above property, like so (the rest of the XAML has been trimmed for space reasons):
<StatusBarItem Grid.Column="0">
<TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Path=StatusMessage}" />
</StatusBarItem>
When I run my application (which hits a couple of DBs in addition to generating a document from template and a bunch of other fairly resource-intensive stuff), some, but not all, messages show up on the status bar. I have debugged and verified that the messages all make it into the StatusMessage property, above (and the ensuing private variable), they just don't seem to be refreshing in the UI.
I have looked at several examples that use BackgroundWorker instances for ProgressBar controls, but haven't seen any for StatusBarItem controls, and am not really sure how to translate one to the other.
I have also used Tasks before in previous C# 4.0 and WPF apps, and figure it's probably a good way to go, but I haven't really been able to figure out how/where to designate the UI task (I've always done it in the code-behind for the MainWindow before, but I'm striving for a zero-code-behind to stay in keeping with MVVM here).
I'm pretty sure that a multi-threaded approach is the way to go; I just don't know enough about one approach (I know a little bit of this and a little bit of that) to make it work. I did see a couple of posts that used the older threading approach directly, but I pretty much stayed away from multithreading programming until I started using Tasks with .NET 4.0 (finding them a little easier to comprehend and keep track of), so I had a bit of trouble making sense of them.
Can anyone take pity on me and point me in the right direction, or suggest further debugging I can do? Thanks!
1)Reflection based binding can be source of error sometimes because of inlining. Try to see what happens if you notifypropertychanged with simple string instead of reflection.
2) if you are using multi threads there maybe a chance that you setup StatusMessage not from UIThread in that case it won't be able to update UI, you could invoke setter code on UI Dispatcher to see if that helps
3) check whether binding works , in constructor of xaml form modify StatusMessage directly on VM and see whether the change is shown on UI without invoking multithreaded service calls which introduce additional variables to simple textblock - string binding
4) if that doesn't help you could create a simple xaml form with single textblock bind it to your big viewmodel and see what happens, if nothing works you can begin cutting VM class to make it simpler so binding eventually starts to work and you find an error
5) if you think that statusbar is the problem see if single textblock without statusbar (extract xaml part from your example) works
Somewhere the notification does not get through.
I would try :
Add a dummy valueconverter on the textbinding so you can set a breakpoint and see if you are called
Dispatching the property set to set the value at a "better" time - that is sometimes nessesary.
Dispatching the set might do the trick.

MVVM Focus To Textbox

How would I set focus to a TextBox without specifying the name for that TextBox? At the moment I am doing the following
<Window FocusManager.FocusedElement="{Binding ElementName=Username}">
<Grid>
<TextBox Text="{Binding Username}" Name="Username" />
</Grid>
</Window>
Is there any way of doing this without specifying a Name for the TextBox. As I believe in MVVM having a Name element usually means bad design?
As I believe in MVVM having a Name element usually means bad design?
No, it’s not.
The MVVM pattern is not about eliminating all the code from code-behind files.
It is about separating of concerns and increasing the testability.
View related code like focus handling should remain in the code-behind file of the View. But it would be bad to see application logic or database connection management in the code-behind file of the View.
MVVM examples with code in the code-behind files without violating the MVVM pattern can be found at the WPF Application Framework (WAF) project.
The simple way is to set focus in UserControl_Load event
this.txtBox.Focus();
txtBox.Focusable = true;
Keyboard.Focus(txtBox);
MVVM doesn't mean you can not put code in the code behind file.
In fact, Do not let any pattern restrict you to find the best way of coding.
I have documented a "pure MVVM" way to do this in my answer to a similar problem. The solution involves using Attached Properties and a framework for passing interface commands from the ViewModel back to the View.
Code behind should be avoided when possible, even more when it is in the view. I had the same problem and for simple purposes the best answer is this one as it only modifies the view:
WPF MVVM Default Focus on Textbox and selectAll
If you are looking to set again focus as you interact with other UserControl elements, this will do the trick:
Set focus on textbox in WPF from view model (C#)
I lost 3 days figuring this out, I hope this can help.
As I believe in MVVM having a Name element usually means bad design?
No, it’s not.
According to Microsoft MVP's not only is naming controls is WPF bad practice, it is a quite substantial hit on performance. Just wanted to pass along some words of wisdom
I agree with Sean Du about not letting any pattern totally restrict you, I think performance hit should be avoided whenever possible.
Actually, I found the boolean attached property solution a bit dirty and clumsy in the way that you have to find a twist in order to be sure that the next set of your view model property will really raise the attached property changed event.
A simple and more elegant solution is to bind your behavior on property type for which you can be sure that the next value will always be different from the previous one and thus be sure that your attached property changed event will raise every times.
The most simple type that comes into mind is the int. The solution is then the usual combination of :
The behavior:
public static class TextBoxFocusBehavior
{
public static int GetKeepFocus(DependencyObject obj)
{
return (int)obj.GetValue(KeepFocusProperty);
}
public static void SetKeepFocus(DependencyObject obj, int value)
{
obj.SetValue(KeepFocusProperty, value);
}
// Using a DependencyProperty as the backing store for KeepFocus. This enables animation, styling, binding, etc...
public static readonly DependencyProperty KeepFocusProperty =
DependencyProperty.RegisterAttached("KeepFocus", typeof(int), typeof(TextBoxFocusBehavior), new UIPropertyMetadata(0, OnKeepFocusChanged));
private static void OnKeepFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox t = d as TextBox;
if (t != null)
{
t.Focus();
}
}
}
The view model property:
public int InputFocus
{
get { return _inputFocus; }
private set
{
_inputFocus = value;
Notify(Npcea.InputFocus);
}
}
The use of the attached behavior:
<TextBox v:TextBoxFocusBehavior.KeepFocus="{Binding InputFocus}"/>
And finaly the use of the property in the VM:
public void YouMethod()
{
//some code logic
InputFocus++;//<= the textbox focus
}
Some REALLY bad minded spirits might say that this logic is bound to the int32 size limitation. Well... I will just choose to ignore them right now ;-)

MouseBinding the mousewheel to zoom in WPF and MVVM

OK, I've figured out how to get my Grid of UI elements to zoom, by using LayoutTransform and ScaleTransform. What I don't understand is how I can get my View to respond to CTRL+MouseWheelUp\Down to do it, and how to fit the code into the MVVM pattern.
My first idea was to store the ZoomFactor as a property, and bind to a command to adjust it.
I was looking at something like:
<UserControl.InputBindings>
<MouseBinding Command="{Binding ZoomGrid}" Gesture="Control+WheelClick"/>
</UserControl.InputBindings>
but I see 2 issues:
1) I don't think there is a way to tell whether the wheel was moved up or down, nor can I see how to determine by how much. I've seen MouseWheelEventArgs.Delta, but have no idea how to get it.
2) Binding to a command on the viewmodel doesn't seem right, as it's strictly a View thing.
Since the zoom is strictly UI View only, I'm thinking that the actual code should go in the code-behind.
How would you guys implement this?
p.s., I'm using .net\wpf 4.0 using Cinch for MVVM.
the real anwser is to write your own MouseGesture, which is easy.
<MouseBinding Gesture="{x:Static me:MouseWheelGesture.CtrlDown}"
Command="me:MainVM.SendBackwardCommand" />
public class MouseWheelGesture : MouseGesture
{
public MouseWheelGesture() : base(MouseAction.WheelClick)
{
}
public MouseWheelGesture(ModifierKeys modifiers) : base(MouseAction.WheelClick, modifiers)
{
}
public static MouseWheelGesture CtrlDown =>
new(ModifierKeys.Control) { Direction = WheelDirection.Down };
public WheelDirection Direction { get; set; }
public override bool Matches(object targetElement, InputEventArgs inputEventArgs) =>
base.Matches(targetElement, inputEventArgs)
&& inputEventArgs is MouseWheelEventArgs args
&& Direction switch
{
WheelDirection.None => args.Delta == 0,
WheelDirection.Up => args.Delta > 0,
WheelDirection.Down => args.Delta < 0,
_ => false,
};
}
public enum WheelDirection
{
None,
Up,
Down,
}
I would suggest that you implement a generic zoom command in your VM. The command can be parameterized with a new zoom level, or (perhaps even simpler) you could implement an IncreaseZoomCommand and DecreaseZoomCommand. Then use the view's code behind to call these commands after you have processed the event arguments of the Mouse Wheel event. If the delta is positive, zoom in, if negative zoom out.
There is no harm in solving this problem by using a few lines of code behind. The main idea of MVVM is that, you are able to track and modify nearly the complete state of your view in an object that does not depend on the UI (enhances the testability). In consequence, the calculation of the new viewport which is the result of the zoom should be done in the VM and not in code behind.
The small gap of testability that exists in the code behind can either be disregarded or covered by automatic UI tests. Automatic UI tests, however, can be very expensive.
If you don't want to use code behind you can use the EventToCommand functionality of mvvm light:
View:
<...
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
...>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseWheel">
<cmd:EventToCommand Command="{Binding
Path=DataContext.ZoomCommand,
ElementName=Root, Mode=OneWay}"
PassEventArgsToCommand="True" />
</i:EventTrigger> </i:Interaction.Triggers>
ViewModel:
ZoomCommand = new RelayCommand<RoutedEventArgs>(Zoom);
...
public void Zoom(RoutedEventArgs e)
{
var originalEventArgs = e as MouseWheelEventArgs;
// originalEventArgs.Delta contains the relevant value
}
I hope this helps someone. I know the question is kind of old...
I think what your trying to do is very much related to the view so there is no harm in putting code in your code behind (in my opinion at least), although I'm sure there are elegant ways of handling this such that it is more viewmodel based.
You should be able to register to the OnPrevewMouseWheel event, check if the user has got the control key pressed and change your zoom factor accordingly to get the zooming effect you are looking for.
I agree with both answers, and would only add that to use code behind is the only way in this case, so you don't even have to think about if it breaks any good practices or not.
Fact is, the only way to get hold of the MouseEventArgs (and thus the Delta) is in the code behind, so grab what you need there (no logic needed for that) and pass it on to your view model as olli suggested.
On the flip side you may want to use a more generic delta (e.g. divide it by 120 before you pass it as a step to the view model) in order to keep it ignorant of any conventions related to the view or the OS. This will allow for maximum reuse of your code in the view model.
To avoid the whole problem, there is one more option :
-use a ContentPresenter in the xaml and let it's content be bound to a viewmodel object.
-handle the mousewheel events within the viewmodel.

Resources