WPF CheckBox's IsChecked property doesn't match binding source's value - wpf

In my WPF application I have a CheckBox whose IsChecked value is bound to a property in my viewmodel. Notice that I have commented out the actual line which sets the value in my viewmodel. It's the standard pattern:
View.xaml
<CheckBox IsChecked="{Binding Path=SomeProperty}" />
ViewModel.cs
public bool SomeProperty
{
get { return this.mSomeProperty; }
set
{
if (value != this.mSomeProperty)
{
//this.mSomeProperty = value;
NotifyPropertyChanged(new PropertyChangedEventArgs("SomeProperty"));
}
}
}
When I click the CheckBox I expect nothing to happen, since the value of this.mSomeProperty does not get set. However the observed behavior is that the CheckBox is being checked and unchecked regardless of the value of this.mSomeProperty.
What is going on? Why isn't my binding forcing the CheckBox to show what the underlying data model is set to?

Because WPF does not automatically reload from the binding source after updating the source. This is probably partly for performance reasons, but mostly to handle binding failures. For example, consider a TextBox bound to an integer property. Suppose the user types 123A. WPF wants to continue showing what the user typed so that they can correct it, rather than suddenly resetting the TextBox contents to the old value of the property.
So when you click the CheckBox, WPF assumes that it should continue to display the control state, not to re-check the bound property.
The only way I've found around this, which is not very elegant, is to raise PropertyChanged after WPF has returned from calling the property setter. This can be done using Dispatcher.BeginInvoke:
set
{
// ...actual real setter logic...
Action notify = () => NotifyPropertyChanged(...);
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, notify);
}
This could be made a bit less horrible by consolidating it into the NotifyPropertyChanged implementation so that you wouldn't have to pollute individual properties with this implementation concern. You might also be able to use NotifyOnSourceUpdated and the SourceUpdated attached event, but I haven't explored this possibility.

Related

wpf binding: The calling thread cannot access this object because a different thread owns it

I am getting this error after raising NotifyPropertyChange event from a view model property.
I added (as a test) an UI Dispatcher.Invoke call on the setter which seems to have fixed the problem temporarily.
public FeedTrackingSummary SelectedFeedTracking {
get { return _selectedFeedTracking; }
set {
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
_selectedFeedTracking = value; Notify("SelectedFeedTracking");
}));
}
}
SelectedFeedTracking below is set by choosing a dropdown value which is bound to this property:
<ComboBox... SelectedItem="{Binding SelectedFeedTracking}" />
the error happens after selecting a drop-down value. There is no other code setting this property. I guess my viewmodel is used in a background thread at the time this happens?
UPDATE
i tried removing the call to INotifyPropertyChanged, and set a totally different property, and the error still persists. so i guess this has to do with the accessibility of the whole viewmodel ?
set {
SelectedCalc = -1;
}
Some MVVM Frameworks (such as Caliburn.Micro, for example) have a base NotifyPropertyChanged class which automatically marshals property change notifications (by raising the PropertyChanged event) to the so-called "UI Thread".
So, instead of having to Application.Current.Dispatcher.Invoke(...) on every property setter, put that code in your Notify() method. Thus making sure every time you notify property changes in the ViewModel you do so in the UI thread.

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.

Set UpdateSourceTrigger to Explicit in ShowDialog (WPF MVVM)

I saw this example - Binding.UpdateSourceTrigger Property
in the example the UpdateSourceTrigger set to Explicit and then in the view code he call to UpdateSource of the TextBox name.
But if i use the MVVM dp i dont want to have names to my controls and source properties are in the VM and not in the view so what is the right way to bind controls to VM properties and set the UpdateSourceTrigger to explicit?
I want to do this because in my case its ShowDialog window and I want that the source will update only if the user click "ok"
Thanks in advance!
If you are using MVVM truely then your OK button click must be handled by some Command. This command must be coming from your ViewModel. The Expliticly bound properties must be coming from your ViewModel again. So whats stopping you.
Do not use Explicit binding but use OneWay binding.
In you button, bind a command and bind a command parameter to the OneWay bound Dependency property.
In your Command's Execute handler (which must be some method from your ViewModel), change the ViewModel's property with the parameter coming.
Raise the NotifyPropertyChanged for that property from your ViewModel.
E.g.
Assume I need to update a TextBox's Text back into my model on OK button click.
So for that I have a EmployeeViewModel class that has EmployeeName property in it. The property is has a getter and a setter. The setter raises property changed notification. The view model also has another property of type ICommand named SaveNameCommand that return a command for me to execute.
EmployeeViewModel is the data context type of my view. Myview has a TextBox (named as x:Name="EmployeeNameTxBx") OneWay bound to the EmployeeName and a Button as OK. I bind Button.Command property to EmployeeViewModel.SaveNameCommand property and Button.CommandParameter is bound to EmployeeNameTxBx.Text property.
<StackPanel>
<TextBox x:Name="EmployeeNameTxBx"
Text="{Binding EmployeeName, Mode=OneWay}" />
<Button Content="OK"
Command="{Binding SaveNameCommand}"
CommandParameter="{Bidning Text, ElementName=EmployeeNameTxBx}" />
</StackPanel>
Inside my EmployeeViewModel I have OnSaveNameCommandExecute(object param) method to execute my SaveNameCommand.
In this perform this code...
var text = (string)param;
this.EmployeeName = text;
This way ONLY OK button click, updates the TextBox's text back into EmployeeName property of the model.
EDIT
Looking at your comments below, I see that you are trying to implement Validation on a UI. Now this changes things a little bit.
IDataErrorInfo and related validation works ONLY IF your input controls (such as TextBoxes) are TwoWay bound. Yes thats how it is intended. So now you may ask "Does this mean the whole concept of NOT ALLOWING invalid data to pass to model is futile in MVVM if we use IDataErrorInfo"?
Not actually!
See MVVM does not enforce a rule that ONLY valid data should come back. It accept invalid data and that is how IDataErrorInfo works and raises error notfications. The point is ViewModel is a mere softcopy of your View so it can be dirty. What it should make sure is that this dirtiness is not committed to your external interfaces such as services or data base.
Such invalid data flow should be restricted by the ViewModel by testing the invalid data. And that data will come if we have TwoWay binding enabled. So considering that you are implementing IDataErrorInfo then you need to have TwoWay bindings which is perfectly allowed in MVVM.
Approach 1:
What if I wan to explicitly validate certain items on the UI on button click?
For this use a delayed validation trick. In your ViewModel have a flag called isValidating. Set it false by default.
In your IDataErrorInfo.this property skip the validation by checking isValidating flag...
string IDataErrorInfo.this[string columnName]
{
get
{
if (!isValidating) return string.Empty;
string result = string.Empty;
bool value = false;
if (columnName == "EmployeeName")
{
if (string.IsNullOrEmpty(AccountType))
{
result = "EmployeeName cannot be empty!";
value = true;
}
}
return result;
}
}
Then in your OK command executed handler, check employee name and then raise property change notification events for the same property ...
private void OnSaveNameCommandExecute(object param)
{
isValidating = true;
this.NotifyPropertyChanged("EmployeeName");
isValidating = false;
}
This triggers the validation ONLY when you click OK. Remember that EmployeeName will HAVE to contain invalid data for the validation to work.
Approach 2:
What if I want to explicitly update bindings without TwoWay mode in MVVM?
Then you will have to use Attached Behavior. The behavior will attach to the OK button and will accept list of all items that need their bindings refreshed.
<Button Content="OK">
<local:SpecialBindingBehavior.DependentControls>
<MultiBinding Converter="{StaticResource ListMaker}">
<Binding ElementName="EmployeeNameTxBx" />
<Binding ElementName="EmployeeSalaryTxBx" />
....
<MultiBinding>
</local:SpecialBindingBehavior.DependentControls>
</Button>
The ListMaker is a IMultiValueConverter that simply converts values into a list...
Convert(object[] values, ...)
{
return values.ToList();
}
In your SpecialBindingBehavior have a DependentControls property changed handler...
private static void OnDependentControlsChanged(
DependencyObject depObj,
DependencyPropertyChangedEventArgs e)
{
var button = sender as Button;
if (button != null && e.NewValue is IList)
{
button.Click
+= new RoutedEventHandler(
(object s, RoutedEventArgs args) =>
{
foreach(var element in (IList)e.NewValue)
{
var bndExp
= ((TextBox)element).GetBindingExpression(
((TextBox)element).Textproperty);
bndExp.UpdateSource();
}
});
}
}
But I will still suggest you use my previous pure MVVM based **Approach 1.
This is an old question but still I want to provide an alternative approach for other users who stumble upon this question...
In my viewmodels, I do not expose the model properties directly in the get/set Property methods. I use internal variables for all the properties. Then I bind all the properties two-way. So I can do all the validation as "usual" because only the internal variables are changed. In the view model constructor, I have the model object as parameter and I set the internal variables to the values of my model. Now when I click on the "Save" Button (-> Save Command fires in my view model fires) and there are no errors, I set all the properties of my model to the values of the correspondng internal variable. If I click on the "Canel/Undo"-Button (-> Cancel-Command in my view model fires), I set the internal variables to the values of my untouched model (using the setters of the view model properties so that NotifyPropertyChanged is called and the view shows the changes=old values).
Yet another approach would be to implement Memento-Support in the model, so before you start editing you call a function in the model to save the current values, and if you cancel editing you call a function to restore those values...that way you would have the undo/cancel support everywhere an not just in one view model...
I've implemented both methods in different projects and both work fine, it depends on the requirements of the project...

Why won't my WPF bound Visibility property update?

I have a textblock in my XAML where the Visibility is bound to a property in my viewmodel. When the window first loads, the value from the viewmodel determines the visibility correctly (I tried manually overriding the backing store variable value and it works great, hiding the control as I need). However, when I change the property value the visibility doesn't change.
Here's the XAML for the control:
<TextBlock Text="Click the button" Style="{StaticResource Message}" Visibility="{Binding NoResultsMessageVisibility}" />
The "NoResultsMessageVisibility" property that I bind to is this:
public Visibility NoResultsMessageVisibility
{
get { return _noResultsMessageVisibility; }
set
{
_noResultsMessageVisibility = value;
NotifyPropertyChanged("NoResultsMessageVisibility");
}
}
NotifyPropertyChange raises a PropertyChanged event for the provided name using standard INotifyPropertyChanged.
Can anyone spot my mistake?
EDIT
In response to the comments / answer so far.
The program is super simple so there's no parallelism / multithreading used.
The DataContext is set only once when the window loads, using:
new MainWindow { DataContext = new MainWindowViewModel() }.ShowDialog();
The binding does seem to work when first loaded. I've noticed as well that a textbox I have bound to a property isn't updating when I change the property. However, the property is definitely updating when I change the textbox as the value is used as the basis for a command that's bound to a button. As the text changes, the button is enabled and disabled correctly and when I click it the value from the property is correct. Again, if I set a value against the backing store variable, this shows in the textbox when the window first loads.
Don't see anything wrong with this, is it possible that the DataContext gets changed, so the binding breaks? (You only specify the path, so it's relative to the current DataContext)
Solved it. I'm a dozy dork :)
I have copied some code from another class and for some reason I'd added the PropertyChanged event to my viewmodel's interface, rather than implementing INotifyPropertyChanged on the interface. D'Oh!

WPF ToggleButton binding IsChecked when disabled

This is a bit of a wierd problem. (.NET 3.5sp1)
I have a UserControl containing three ToggleButtons, each with IsChecked bound to different dependency properties on the UserControl itself. Two of these default to true, one defaults to false.
On startup of the application, the UserControl itself (and thus its contents) is disabled. When it gets enabled later on, all three buttons appear un-pressed; however the code properties are still in the correct state.
If the buttons are clicked then the properties will toggle properly and the UI (for that button only) will update to reflect the correct state (ie. clicking on a button which appears un-pressed but has a true bound value will show no visible change the first time, but updates the bound value to false). Pressing a "glitched" button for the second time will behave normally (if it toggles on, the button will press in as expected).
If the UserControl is not disabled on startup, then the buttons will appear correctly (according to the state of the properties).
Unfortunately the UserControl is supposed to be disabled on startup, so I can't really start up with it enabled; I'm hoping for an alternate solution. Any ideas?
(I've tried making the properties default to false and then setting them to true in the user control's Load event. Doesn't make any difference.)
The same weird problem happens in .NET 4.0 as well. I noticed that the problem only occurs if you set IsEnabled through code and not if you bind it, so if you can change your code to that instead I believe your problem will be solved.
Otherwise, I believe a workaround is necessary and here is one way to do it. Reset the DataContext for the UserControl the first time IsEnabled is set to True.
public UserControl1()
{
InitializeComponent();
DependencyPropertyDescriptor descriptor =
DependencyPropertyDescriptor.FromProperty(UserControl1.IsEnabledProperty,
typeof(UserControl1));
EventHandler isEnabledChanged = null;
isEnabledChanged = new EventHandler(delegate
{
if (IsEnabled == true)
{
descriptor.RemoveValueChanged(this, isEnabledChanged);
var dataContext = this.DataContext;
this.DataContext = null;
this.DataContext = dataContext;
}
});
descriptor.AddValueChanged(this, isEnabledChanged);
}
I came across a 'somewhat' similar situation and the following SO reply proved to be more appropriate in my case. It save me a lot of troubles and so, just in case anyone looking at this solution hasn't noticed it, I think a reference to it should be useful here.
WPF ToggleButton incorrect render behavior
Cheers
Mansoor

Resources