Data validation on a ListBox in WPF - wpf

I have a ListBox bound to an ObservableCollection of type T - each ListBoxItem is a checkbox with IsChecked bound to a bool property in T. I want to validate the checked items in the ListBox so that at least one checkbox must be ticked - if none of the check boxes are ticked I want to show a red border (standard validation notification) around the ListBox.
How do I go about doing that? Can I use ValidatesOnDataErrors?

Implement IDataErrorInfo in the class that exposes the ObservableCollection<T> property and make the indexer return an error for that property's name if all of the objects in the collection have a value of false in their boolean property. Then use the DataErrorValidationRule in your binding's ValidationRules.

Your goal is to validate selected items of a ListBox: at least one selected item is required. First, there are different ways to handle the selection itself:
a) You can use the ListBox selection mechanism via ListBox.SelectedItem.
I guess, you can specifiy the binding as SelectedItem="{Binding SelectedThing, ValidatesOnNotifyDataErrors=True}" and WPF's regular validation works. Not sure, if this works well with multi-selection.
b) You can use ListBox.SelectedItems. Binding is not possible and needs to be faked via code behind event handler. Thus, WPF's validation cannot trigger here.
c) You use your own IsSelected property (or similar) per item, either explicitely bound to your viewmodel via CheckBox or implicitely via ListBoxItem.IsSelected (via ListBox.ItemContainerStyle).
From here you could create a bool IsValidSelection property in your viewmodel that updates whenever the selection changed. Or you can run validation rules on any of the resulting properties of your viewmodel (e.g. SelectedItems). However, you don't validate the bound ListBox.ItemSource itself! Therefore WPF's standard mechanisms don't work (the list box doesn't get a red border or whatever).
Workarounds
You can explicitely create error notifications by showing an otherwise invisible Label and binding its visibility to the above-mentioned bool IsValidSelection property. This is a very explicit way, not using WPF validation at all.
You can modify your INotifyDataErrorInfo (or similar) implementation to trigger errors on a different property name. This is not possible, if you use a generic ValidatableViewModel<T> (like me). I guess this was the intention of the other answer.

Related

Is it the right way that command parameter references a view control in MVVM pattern?

I'm making a page using MVVM pattern.
By the way, I had a question during implementing command.
It is 'Is it the right to send command parameter to UI control'?
For example, I have a TextBox control. When LostFocus event is fired, a validation command binded with TextBox will be raised and I will send an UI control as command parameter to display a validation failure message.
After a command is executed, I will change content value of UI control if validate is failed.
These are my scenario.
But I know a viewmodel should not reference any of views and its controls directly.
Please let me know how.
If your validation is evaluated in the code behind of your view/control then you are fine to send or pass a control.
I have to question what sort of validation is being done at the UI layer - it can be general input logic (like numbers only or only certain letters, etc), but it shouldn't involve any business logic. Your code behind could call a method on the viewmodel to perform business logic based validation, but it should avoid passing a control.
If you are simply looking for a way to make a generic validation method for multiple controls, then you should consider another way such as:
creating a custom usercontrol that has the validation
using an attached behavior
A view model should not have any references or any dependencies upon any UI control such as a TextBox.
Instead of passing a reference to the TextBox as a command parameter to the view model command, you should either pass the value of the Text property of the TextBox as a string argument or - even better - you should simply bind the Text property of the TextBox to a string source property of the view model:
<TextBox Text="{Binding YourViewModelProperty}" />
The source property will be set when the TextBox loses focus and you can easily kick off your validation logic in the setter:
private string _s;
public string YourViewModelProperty
{
get { return _s; }
set { _s = value; Validate(); }
}
This is how the MVVM pattern is supposed to be implemented.

How do you handle enable/disable support for non-ICommand bound Controls?

On my view I have different Controls. Mostly Buttons, TextBoxes and ComboBoxes. The Buttons are enabled/disabled via CommandBinding (ICommand), but the other controls must be enabled/disabled "manually". I can think of many ways to achieve this:
Adding a bool-Property to the ViewModel is one way and using DataTriggers is an other. (Or maybe I could bind the Property directly and use a IValueConverter.)
Is there a particular solution in MVVM that I am leaving out or missing?
Yes, you can bind a public boolean property on your view model to the IsEnabled property of the control. There is no need for a value converter.

Accessing controls from within commands in WPF

I've got a WPF app who's menu is using the commanding capabilities. Everything is wired up just fine and when I click the buttons in the menu, the commands run. However I'm having trouble getting the button's IsEnabled status to respect the CanExecute part of my commands.
One challenge is the commands need to see what you're doing in the UI. For instance, one command should only be available when certain items in a ListBox are selected so I need to get a reference to the ListBox... but since the command is exposed in my view model (MVVM pattern), it doesn't have access to the UI (BTW, the menu is in one user control [parent=mainwindow] while the ListBox is in another user control [parent=mainwindow]).
In addition, even when I hard code the command's CanExecute method to return false, the Enabled property of the button doesn't change... the command won't fire, but it won't change... frustrating. I assume I need to modify/raise the CanExecuteChanged event, but I'm not sure when I should be doing that (can't find a good sample).
Feedback?
Try the Messenger class from MVVMLight. It helps in communicating between ViewModels.
And give this a try:
Have a SelectedItem property in your ListBox's ViewModel. Broadcast messages while the property changes. Register for this message in the menu's ViewModel. Use the SelectedItem property in your CanExecute method for your logic.
Normally, you would bind the Command Property of the MenuItem/Button whatever - that means you still have the CommandParameter to work with - this can then be bound to some other control. However, when the two views do not know each-other, you need som kind of mediator between them (ie. a viewmodel that both views can access - have the listbox SelectedItem/SelectedItems bound to a property two-ways - and let the CommandParameter bind to the same property one-way).
As for when to fire the CanExecuteChanged event - you should fire that whenever there is a change in the logic contained in the CanExecute-method. If it is always false, you should never fire the event, as it will read the initalvalue when the Command-parameter is set. '
If your button is behaving oddly - check to see if the IsEnabled property is influenced by Styles or set directly.
Hope this helps.

WPF: Bindings - Object not updated

I have a an object which is set to the DataContext in a Window. I have textboxes in the window which are bound to the properties on the object. There seems to be a delay however before the properties on the object are updated.
<TextBox x:Name="txtPropertyOne" Text="{Binding Path=PropertyOne,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
If I change the values in a few textboxes then quickly try to access the properties to which they map, sometimes there are changes which aren't reflected in the properties of the object. I thought that was what the PropertyChanged UpdateSourceTrigger was supposed to take care of.
If I change the values in a few
textboxes then quickly try to access
the properties to which they map
I can interpret this statement in two ways:
You're trying to access the values on a background thread. In that case, you may be accessing the properties before the UI thread has had a chance to do its thing.
You're using a separate message on the UI thread to check the values. Bindings are updated at a priority lower than Send and Normal. So if your message is priority Send or Normal it will be processed before any pending binding updates.
If this doesn't answer your question, please clarify what you mean by "quickly trying to access the properties".
The basic rule of WPF Databinding is simple:
The target property must be a
dependency property, and you're
already correct, it's bound to Text
property of TextBox.
The source property can be a CLR
object (other than any derived WPF's
DependencyObject), but the object
must employ or implement its own
INotifyPropertyChanged.
Have you you already implemented INotifyPropertyChanged on your object?

BindableAttribute, Combobox, Selectedvalue property - WinForms

I am deriving from combobox (WinForms) and am providing a new implementation for the Selectedvalue property.
It works fine as is, but any change to the selectedvalue property is not updating other controls bound to the same "binding context" to change their values accordingly.
I did try adding the BindableAttribute(true) to the property, but still it does nottrigger the change in value to the other linked controls.
The control's DataBindings.add(...) is all set up. And other controls are also bound to the same data filed on the same datasource.
Any ideas what i am doing wrong.
Have you called your base class' implementation of overridden methods? It's possible that failing to call the base class implementation is accidentally circumventing the code that fires various event plumbing.

Resources