How do I make the IsEnabled property of a button dependent on the presence of data in other controls? (WPF) - wpf

I have a "Login" button that I want to be disabled until 3 text boxes on the same WPF form are populated with text (user, password, server).
I have a backing object with a boolean property called IsLoginEnabled which returns True if and only if all 3 controls have data. However, when should I be checking this property? Should it be on the LostFocus event of each of the 3 dependent controls?
Thanks!
vg1890

I'd get the "backing object" to raise the IsLoginEnabled changed event when any of the 3 fields are updated. You can then bind the button to the IsLoginEnabled property and not have to keep checking it.
The pseudocode would look something like this:
Public Event IsLoginEnabledChanged As EventHandler
Public Property User() As String
Get.. ' snipped for brevity
Set(ByVal value As String)
mUser = value
RaiseEvent IsLoginEnabledChanged(Me, New EventArgs())
End Set
' do the same in the Set for Password() and Server() properties
The trick to this is naming the Event [PropertyName]Changed (i.e. IsLogonEnabledChanged) - because raising this event will automagically notify any bound controls :o)

Yes, I would say the easiest option would be to check it on the LostFocus or TextChanged event of each of those controls. However, if you want to do a little heavier lifting, you could implement the boolean as a dependency property that you could have bound to the button's Enable.
http://msdn.microsoft.com/en-us/library/ms750428.aspx

Can you just databind your IsLoginEnabled right to the Enabled property of the login button?

I think you could use RoutedCommands one of the most useful features of WPF. Basically add a CommandBinding, to use OnExecute and OnQueryCommandEnabled to manage button's enabled state.
Check out this wonderful explanation on using RoutedCommands in WPF

Related

Silverlight RadComboBox keeping open after selection

Silverlight MVVM. I have a RadCombobox, and for each selection I'm adding a new row in another datagrid. I add necessaries codes in my ViewModel class and this part is working. What I’d like to perform is:
Keep the comboBox open while the control has the focus in order to allow the user repeating selection (I bind IsDropDownOpen to a method and setting in SelectedItem property to true but still it closes after selection )
Unselect the Item selected to allow duplication selection. I added the event SelectionChanged and add code in MainPage.xaml.cs but looking for a solution within my ViewModel.
Lets say,
IsDropDownOpen = {Binding IsDropDownFromViewModel}
Also, assuming that the getter of IsDropDownFromViewModel is encompassing all your conditions for the drop down to be open, and will always return the correct drop down state.
Now all that you will need to do is fire the PropertyChanged event for this property wherever/whenver you think the drop down should have been open, but is closed, or vice versa.
Unfortunately I didn't get your exact scenario, but lets assume this is the case (You should be use a similar approach to fix whatever problem you have).
Example Scenario:
The drop down closes when you select an item, it is intended to stay open
In the above case, one the user selects an item, the setter for the selectedItem's corresponding binding property should be invoked, so that is where we write the notification code
public SelectedItemType SelectedItemInViewModel {
get{
return _selectedItemVM;
},
set{
_selectedItemVM=value;
NotifyPropertyChanged("IsDropDownFromViewModel");
}
}
What this does is, it will tell the radComboBox's IsDropDownOpen property to reevaluate it's binding expression on the RHS and get its new value
Hope you get the gist of the approach, if not leave a comment.

wpf: TextChanged event fired on setting DataContext

I've got a simple View with a single textbox that gets databound to a simple ViewModel with a single string property.
I need to catch the TextChanged event of that textbox so that I can do a little validation magic.
The problem that I am running into is that the TextChanged event fires for that textbox when the DataContext is set for the View.
Is there a standard mechanism that I can use to determine if the event is firing because of the DataContext being set versus when the user is making changes?
Thanks!
As far as I know there is no such mechanism. What you should do instead is to do your validation magic using standard means of WPF. Please see the following link: http://msdn.microsoft.com/en-us/library/ms752347.aspx#data_validation.
Anyway, as long as you use MVVM you can always detect that text has changed in the setter of the bound property in your view model.

S/L 4 & IDataErrorInfo - How to force re-validation of a control (when a related control is touched)

I have two controls bound to properties MinCartValue and MaxCartValue. MinCartValue must be less than MaxCartValue. To achieve this validation I have implemented the the IDataErrorInfo interface, and run the above check in the this[columnName] method if either MinCartValue or MaxCartValue are touched. ValidatesOnDataErrors=True is set in the binding of both controls.
The validation works correctly, highlighting each control when a change to its property value violates the rule. The problem is that once a control is flagged as invalid, if the user corrects the problem by altering the other control's value, the first control remains flagged as invalid. This is understandable because the IDataErrorInfo method was not doing validation on the first control's property.
So what I need is a way to force property #1 to be re-validated (or a way to clear the invalid state) when property #2 is validated, and vice versa. I have tried calling RaisePropertyChanged within my this[columnName] method but it does nothing. Also tried setting the property to its own value to try to trick it to validate itself, but again nothing happens.
Thanks
I would recommend looking at the INotifyDataErrorInfo interface (introduced in Silverlight 4). It's able to async-notify if properties become invalid, so I think the framework is better about respecting this across many properties instead of expecting that the property currently being changed is the only one whose validity may be changing.
I had two DateTime properties (DateFrom and DateTo) that needed to be validated against each other. In the setters for these properties I just raised a PropertyChanged event for both DateTo and DateFrom. Worked like a charm.
I'm not sure if I'm understanding your problem exactly, but perhaps this may help. Providing some example XAML and the binding property code would help.
It sounds like an issue of your code depending on the default UpdateSourceTrigger, which in the case of TextBox controls is their focus/unfocus. You can set in the XAML the UpdateSourceTrigger attribute by adding UpdateSourceTrigger=Explicit to your binding where your validation occurs. Then in each TextBox (MinCartValue, MaxCartValue), add an event handler to the TextChanged event.
In the code-behind in the event handler, you can do something like this:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TheTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
TheTextBox in this case would be one of your cart controls. The UpdateSource() method is a way to manually update the binding value, which should trigger your validation. This method provides away to tie into a trigger to update values and raising properties have changed outside of the default scope (using text changed intead of focus and unfocus on TextBox in this instance).
Here's how I solved it. Let's say Property1 and Property2 are codependent. I'm not familiar with MVVM (yet), but you're probably extending your entity class to implement IDataErrorInfo. In this case you can also extend On[Property]Changed method and report change in codependent property:
partial class YourEntity : IDataErrorInfo
{
public string this[string columnName]
{
//Your validation logic
}
public string Error
{
//WPF doesn't use it anyway
get { return string.Empty; }
}
partial void OnProperty1Changed()
{
OnPropertyChanging("Property2");
OnPropertyChanged("Property2");
}
partial void OnProperty2Changed()
{
OnPropertyChanging("Property1");
OnPropertyChanged("Property1");
}
}
In this case the update in either one of this properties makes both bound controls re-evaluate themselves.
EDIT2: It appears that you should use OnPropertyChang* instead of ReportPropertyChang*. ReportPropertyChanged will notify the entity framework that there are pending changes in the model, but in fact all you're trying to do is inform the view. You don't want to update the database with the property that didn't really change. ReportPropertyChang* will also fail on computed fields that have no mappings in the database.
EDIT1: Found out that it's essential to call ReportPropertyChanging before ReportPropertyChanged.

WPF MVVM UpdateSourceTrigger=Excplict

i've a contentcontrol in my Wpf-App (MVVM) which is bound to an object and displays the objects properties in textboxes, so the user can edit the values of the properties.
I want to implement undo/redo functionality with the command pattern of the GoF.
For this i need a point where i can create the command and set it into my undomanager.
My idea was to add a submitbutton. When the button is pressed, i update the sources of the textboxes (my properties) and create my command object to make the changes undoable (saving the old state of the object and the new state).
But:
- For using a submit button i need to set UpdateSourceTrigger of the textboxes to Explicit. If i want to update my sources i need to reference the controls in my view, which is bad as far as i've learned. How can i do that?
With MVVM i have to create a Command (WPF Command, not my undo redo command) for the SubmitButton but i don't see how to apply the changes to the properties from that command without referencing the textboxes (further hey are generated via datatemplates).
Thanks Walter
I assume your TextBox controls are bound to the properties in the ViewModel class. If you bind your submit button to a ViewModel Command which in turn can add appropriate command to you Command Pattern Collection and also changes some of ViewModel properties, the values in the Textbox controls will also be updated. Now, for a Textbox to update it's value when the value of a property it is bound to changes, the ViewModel class needs to implement INotifyPropertyChanged interface and raise the PropertyChanged event from the property setter with that's property's name as an argument.

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.

Resources