Two way binding settings problem - c#

I am having a problem using two way binding with a listpicker. I am able to set the value using c# but not in the SelectedItem=".." in xaml. The binding is returning the correct value (and is a value in the listpicker) as i have texted it by assigning the text to a textblock.
When the page loads, the binding used on the listpicker causes a System.ArgumentOutOfRangeException
The code i am using to set it is:
// Update a setting value. If the setting does not exist, add the setting.
public bool AddOrUpdateValue(string key, Object value)
{
bool valueChanged = false;
try
{
// If new value is different, set the new value
if (settingsStorage[key] != value)
{
settingsStorage[key] = value;
valueChanged = true;
}
}
catch (KeyNotFoundException)
{
settingsStorage.Add(key, value);
valueChanged = true;
}
catch (ArgumentException)
{
settingsStorage.Add(key, value);
valueChanged = true;
}
catch (Exception e)
{
Console.WriteLine("Exception occured whilst using IsolatedStorageSettings: " + e.ToString());
}
return valueChanged;
}
// Get the current value of the setting, if not found, set the setting to default value.
public valueType GetValueOrDefault<valueType>(string key, valueType defaultValue)
{
valueType value;
try
{
value = (valueType)settingsStorage[key];
}
catch (KeyNotFoundException)
{
value = defaultValue;
}
catch (ArgumentException)
{
value = defaultValue;
}
return value;
}
public string WeekBeginsSetting
{
get
{
return GetValueOrDefault<string>(WeekBeginsSettingKeyName, WeekBeginsSettingDefault);
}
set
{
AddOrUpdateValue(WeekBeginsSettingKeyName, value);
Save();
}
}
And in the xaml:
<toolkit:ListPicker x:Name="WeekStartDay"
Header="Week begins on"
SelectedItem="{Binding Source={StaticResource AppSettings},
Path=WeekBeginsSetting,
Mode=TwoWay}">
<sys:String>monday</sys:String>
<sys:String>sunday</sys:String>
</toolkit:ListPicker>
The StaticResource AppSettings is a resource from a seperate .cs file.
<phone:PhoneApplicationPage.Resources>
<local:ApplicationSettings x:Key="AppSettings"></local:ApplicationSettings>
</phone:PhoneApplicationPage.Resources>
Thanks in advance

I used Reflector to find the source of this exception. In ListPicker.cs the following method is overridden.
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
In this method the following line will cause the exception if SelectedItem is set and SelectedIndex is -1 (which it is unless it's set before it's loaded). If SelectedItem isn't set this line is never reached (hence no exception).
else if (!object.Equals(base.get_Items().get_Item(this.SelectedIndex), this.SelectedItem))
To work around this (until they get this fixed) I have some suggestions.
Workaround 1
If you know the starting index which will be produced by the TwoWay binding then you can set the SelectedIndex property as well and the TwoWay Binding will work
<toolkit:ListPicker x:Name="WeekStartDay"
Header="Week begins on"
SelectedItem="{Binding Source={StaticResource AppSettings},
Path=WeekBeginsSetting,
Mode=TwoWay}"
SelectedIndex="1">
<sys:String>monday</sys:String>
<sys:String>sunday</sys:String>
</toolkit:ListPicker>
Workaround 2
Use the Loaded event and set the Binding from there instead
<toolkit:ListPicker x:Name="WeekStartDay"
Header="Week begins on"
Loaded="WeekStartDay_Loaded">
<sys:String>monday</sys:String>
<sys:String>sunday</sys:String>
</toolkit:ListPicker>
private void WeekStartDay_Loaded(object sender, RoutedEventArgs e)
{
Binding binding = new Binding();
binding.Source = this.Resources["AppSettings"] as ApplicationSettings;
binding.Path = new PropertyPath("WeekBeginsSetting");
binding.Mode = BindingMode.TwoWay;
WeekStartDay.SetBinding(ListPicker.SelectedItemProperty, binding);
}

Are you Firing the relevant property changed events?
Make sure that SelectedItem can have a two way binding.If not then try defining an ItemContainerStyle and bind the IsSelected property to a corresponding property on your object.Getting the selected item then becomes trivial.

If AppSettings is a collection then this is not going to work. You need to bind SelectedItem to a scalar value and unfortunately the "Silverlight 3.7" on WP7 doesn't support indexers in bindings.
Also, please don't use exceptions as flow control in your program, instead do something like this:
try
{
// If new value is different, set the new value
if(!settingsStorage.ContainsKey(key))
{
settingsStorage.Add(key, value);
valueChanged = true;
}
else if(settingsStorage[key] != value)
{
settingsStorage[key] = value;
valueChanged = true;
}
}
catch (Exception e)
{
Console.WriteLine("Exception occured whilst using IsolatedStorageSettings: " + e.ToString());
}

Instead of using binding I simply set the selecteditem when the page loaded and used a selectionchanged event handler to update the value without confirmation (having a save button).

Related

WPF Validation Rule on ComboBox calling the Setter of binded propery twice

I have a ComboBox like this:
<ComboBox Name="TipoVisitante" ItemsSource="{Binding TiposVisitante}" SelectedValue="{Binding TipoVisitante}" Style="{StaticResource ComboBoxStyle}">
<ComboBox.Text>
<Binding Path="TipoVisitante" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validations:SimpleIsRequiredValidation/>
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
This ComboBox is binded to the TipoVisitante property from the ViewModel. The TipoVisitante variable looks like this:
private string _TipoVisitante;
public string TipoVisitante {
get =>_TipoVisitante;
set {
if (ValidarTipoVisita(value) == true) {
_TipoVisitante = value;
OnPropertyChanged();
}
else {
MessageBox.Show("YA EXISTE UNA VISITA ÍNTIMA ACTIVA", "VISITA INTIMA ACTIVA", MessageBoxButton.OK, MessageBoxImage.Error);
_TipoVisitante = null;
OnPropertyChanged();
}
}
}
When TipoVisitante is set, I want to check if the value is valid using a method that return true or false depending on which the value is valid or not. If the the values isn't valid, I show a message saying that the value is not valid. The problem is, because of the validation on rule on the ComboBox, the set property of the TipoVisitante variable is called twice, and the error message is shown twice. The Validation Rule of the ComboBox looks like this:
public class SimpleIsRequiredValidation: ValidationRule {
public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
if (!string.IsNullOrEmpty(value ? .ToString()))
return new ValidationResult(true, null);
else
return new ValidationResult(false, null);
}
}
The validation rule checks if the user has selected some value of the combobox, checking if the text is null or a empty string. Also in my code behind I have this:
private void Button_Click(object sender, RoutedEventArgs e) {
if (string.IsNullOrWhiteSpace(TipoVisitante.Text))
TipoVisitante.Text = "";
}
This method is the Click property of a button. When the button is click, I check if the user hasn't selected some value of the ComboBox I set the text to empty string to trigger the validation and show the red border in the ComboBox.
How can I avoid the setter of the binded variable TipoVisitante to be called twice?
Try to add extra property that check was it called once then use it to block call it twice.
The solution was change the validation from ComboBox.Text to ComboBox.SelectedValue. After that in the button Click action, change TipoVisitante.Text = "" to TipoVisitante.SelectedValue = null. Doing that it worked fine.

Combobox value changes, but visually SelectedValue stays the same

I have a combobox with a custom enum (just true/false). I have a function that checks conditions if the SelectedValue changes from false to true and if the conditions are wrong it changes the combobox SelectedValue back to false. This changes the SelectedValue to false if you check it in code, but when you look at the UI it's still on true.
Here's the xaml for the combobox:
<ComboBox x:Name="comboEnabled1" Width="80" Height="26"
ItemsSource="{Binding Path=TrueFalseChoices}"
SelectedValue="{Binding Path=Enable1, Mode=TwoWay}"/>
Here's the viewmodel
private TrueFalse _enable1 = TrueFalse.False;
public TrueFalse Enable1
{
get { return _enable1; }
set
{
if (_enable1 != value)
{
_enable1 = value;
base.OnPropertyChanged("Enable1");
OnEnableChanged(EventArgs.Empty);
}
}
}
And here's the function that I'm using to check the conditions
public void HandleEnable(object sender, EventArgs e)
{
if(Enable1 == TrueFalse.True)
{
if(!connected)
{
HandleMessage("Can't enable, not connected");
Enable1 = TrueFalse.False;
}
else if (!_main.CBCheck(_main.cbReason))
{
Enable1 = TrueFalse.False;
}
}
Console.WriteLine("Enabled {0}", Enable1);
}
Was thinking I'm changing the value too rapidly, but the last Console.Writeline produces the right outcome each time.
Any help appreciated!
Edit: Calling Handleenable here:
protected void OnEnableChanged(EventArgs e)
{
EventHandler handler = EnableChanged;
if (handler != null)
handler(this, e);
}
And in the ViewModel funct:
EnableChanged += HandleEnable;
Changing the Enable1 in any other place worked as it should have, only having issues in HandleEnable function.Also tried changing other comboboxes in the HandleEnable function and that worked as it should have.
I would recommend actually disabling the ComboBox if the requirements are not met.
But if you insist on reverting Enable1 back to False if conditions are not met, you should push the notification properly through the dispatcher.
set
{
var effectiveValue = condition ? value : TrueFalse.False;
if (effectiveValue == TrueFalse.False && value == TrueFalse.True)
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() => base.OnPropertyChanged("Enable1"), null));
//your regular set-code follows here
}
It happens because WPF is already responding to that event, and therefore ignoring the subsequent calls until it's done. So you immediately queue another pass as soon as the current one is finished.
But I would still recommend disabling the ComboBox when it is effectively disabled. Accessing the dispatcher from a viewmodel does not smell good no matter how you look at it.
UPD: You can also solve that with {Binding Enable1, Delay=10} if your framework is 4.5.1+.

Is it better to put my logic in an event handler or in a setter for MVVM (Xamarin `Picker` `SelectedItem` quirks)

SOLUTION IS IN EDIT OF THE ACCEPTED ANSWER
I have a view in which has two Pickers, I need to have it so that when the SelectedItem property in one Picker changes, the list of Items in the second Picker (ItemSource) changes as well.
Currently I have a bound the SelectedItem and SelectedIndex properties of both pickers to properties in my ViewModel. In the setter(s) for both of them, I perform the logic needed to change the list of Items in the second picker. The list of Items in the second picker changes successfully, but when I set the SelectedIndex (to make it select an Item by default), this fails if the index which I am setting it to is the same as the index which it was on in the previous list. It just shows the Title of the Picker instead, this issue seems to be related to this bug.
My Code:
Both Pickers are bound to an Observable collection of strings FYI
FrameType and DirectionType are Enums
I initially used only the SelectedItem property
Relevant XAML
<Label Grid.Row="1" Grid.Column="0" VerticalTextAlignment="Center"
Text="Direction: " />
<Picker x:Name="PickerDirection" Grid.Row="1" Grid.Column="1"
Title="Select Direction"
ItemsSource="{Binding Directions}"
SelectedItem="{Binding SelectedDirection}"
SelectedIndex="{Binding SelectedDirectionIndex}"></Picker>
<Label Grid.Row="2" Grid.Column="0" VerticalTextAlignment="Center"
Text="Frame: "/>
<Picker x:Name="PickerFrame" Grid.Row="2" Grid.Column="1"
Title="Select Frame"
ItemsSource="{Binding Frames}"
SelectedItem="{Binding SelectedFrame}"
SelectedIndex="{Binding SelectedFrameIndex}"></Picker>
Relevant View Model code:
public string SelectedDirection
{
get { return _selectedDirection; }
set
{
if (Directions.Contains(value))
{
if (_selectedDirection != value)
{
if (EnumUtils.ToEnumFromString<FrameType>(SelectedFrame) == FrameType.Road &&
!DirectionsRoad.Contains(value))
{
_selectedDirection = Directions[Directions.IndexOf(DirectionType.Right.ToString())];
}
else
{
_selectedDirection = value;
}
OnPropertyChanged();
}
}
}
}
public string SelectedFrame
{
get { return _selectedFrame; }
set
{
if (_selectedFrame != value)
{
_selectedFrame = value;
if (EnumUtils.ToEnumFromString<FrameType>(_selectedFrame) == FrameType.Road)
{
Directions = DirectionsRoad;
if (Directions.Contains(SelectedDirection))
{
SelectedDirectionIndex = Directions.IndexOf(SelectedDirection);
}
else
{
SelectedDirectionIndex = Directions.IndexOf(DirectionType.Right.ToString());
}
}else if (EnumUtils.ToEnumFromString<FrameType>(_selectedFrame) == FrameType.Lane)
{
Directions = DirectionsAll;
SelectedDirectionIndex = Directions.IndexOf(SelectedDirection);
}
OnPropertyChanged();
}
}
}
}
public int SelectedDirectionIndex
{
get { return _selectedDirectionIndex; }
set
{
if (_selectedDirectionIndex != value)
{
if (!(value < 0 || value >= Directions.Count))
{
_selectedDirectionIndex = value;
OnPropertyChanged();
}
}
}
}
public int SelectedFrameIndex
{
get { return _selectedFrameIndex; }
set
{
if (_selectedFrameIndex != value)
{
if (!(value < 0 || value >= Frames.Count))
{
_selectedFrameIndex = value;
OnPropertyChanged();
}
}
}
}
The outcome:
I expect it to never be empty since I ensure that the SelectedDirection is always set to something.
Notes:
I initially used just the SelectedItem property, but when I encountered this bug I thought using the SelectedIndex property would help to fix it.
I used ObservableCollection to maintain consistency with the other viewModels in the project, and to ensure that the options in the picker are updated when I make changes (based on my understanding you need to use ObservableCollection to make this possible).
I do plan to refactor the code in the setter for SelectedFrame into smaller functions as soon as I get things to work.
Due to this It seems that using the SelectedIndexChanged event of the Picker would be the only way to fix this. However the comment by ottermatic in this question says that events are unreliable. Hence I felt is was better to perform this logic in the setter.
If someone could comment on what I may be doing wrong in my code which is causing this issue and also comment on the pros/cons and/or whether or not I should use the eventHandler or have the logic in my setter. Thanks
I don't really see why you are using both SelectedItem and SelectedIndex, but I think what you are trying to achieve can be achieved easier.
First of all, I don't think you need ObservableCollection types at all in your example, since you are setting the directions anyway and not modifying the collection. More importantly, fiddling around with the indices is completely unnecessary, as far as I can tell. You are using strings anyway and even though String is not a value type, but a reference type, you cannot practically distinguish two String instances that have the same content, hence assinging the respective values to SelectedDirection and SelectedFrame is sufficient.
The following checks seem redundant to me
if (Directions.Contains(value))
if (EnumUtils.ToEnumFromString<FrameType>(SelectedFrame) == FrameType.Road &&
!DirectionsRoad.Contains(value))
since Directions are set to DirectionsRoad anyway if SelectedFrame has been set to "Road". Hence I'd assume that the second condition won't evaluate to true in any case. Hence the SelectedDirection can be simplified:
public string SelectedDirection
{
get => _selectedDirection;
set
{
if (_selectedDirection != value && Directions.Contains(value))
{
_selectedDirection = value;
OnPropertyChanged();
}
}
}
Within the setter of SelectedFrame there are many things going on, which I'd refactor to methods on it's own right, to improve clarity.
public string SelectedFrame
{
get => _selectedFrame;
set
{
if (_selectedFrame != value)
{
_selectedFrame = value;
UpdateAvailableDirections();
OnPropertyChanged();
}
}
}
private void UpdateAvailableDirections()
{
// store the selected direction
var previouslySelectedDirection = SelectedDirection;
Directions = GetValidDirectionsByFrameType(EnumUtils.ToEnumFromString<FrameType>(SelectedFrame));
SelectedDirection = GetSelectedDirection(previoslySelectedDirection, Directions);
}
private string[] GetValidDirectionsByFrameType(FrameType frameType)
{
return frameType == FrameType.Road ? DirectionsRoad : DirectionsAll;
}
private string GetSelectedDirection(string previouslySelectedDirection, string[] validDirections)
{
return validDirections.Contains(previouslySelectedDirection) ? previouslySelectedDirection : DefaultDirection;
}
By setting the SelectedItem instead of fiddling with the indices, the correct values shall be displayed.
Concerning your question whether this logic may be better suited in an event handler or in the setter depends on your requirements. If all you need is the index, the event SelectedIndexChanged may work out for you, but if the value is needed in several places and methods that are not called by the event handler, the presented solution may be more viable.
Edit
You were correct, it has got nothing to do with the usage of SelectedIndex and SelectedItem. The issue is a bit more subtle.
I build a quick proof-of-concept and found the following:
Assuming SelectedDirection is "Right" (and the index is set accordingly)
When Directions is set, the SelectedItem on the picker seems to be reset
SelectedDirection is set to null
this.Directions.Contains(value) evaluates to false, hence _selectedDirection is not set (this hold true for SelectedDirectionIndex, since the value -1 is filtered by if(!value < 0 || value >= this.Directions.Count))
When SelectedDirection is set afterwards, the value is still "Right", hence OnPropertyChanged is not called (since the values are the same) and the SelectedItem is not set
This way there is a mismatch between the value the Picker actually holds and the property in the viewmodel, which leads to unexpected behavior.
How to mitigate the issue?
I'd still stick with the code without the indices (unless you really need them) and use the string values.
There are other possibilities, but I'd change the setter of SelectedDirection. When you allowed the value to be set to null, PropertyChanged will be raised properly when the value is set to Right afterwards. If you really need to filter what the value is set to, you should still raise OnPropertyChanged, to inform the Picker that the value has changed (preventing a mismatch between the actual Pickers value and the viewmodel)
public string SelectedDirection
{
get => _selectedDirection;
set
{
if (_selectedDirection != value)
{
if(Directions.Contains(value))
{
_selectedDirection = value;
}
else
{
_selectedDirection = DirectionTypes.Right.ToString();
}
OnPropertyChanged();
}
}
}
Found a somewhat hacky fix for this, and it seems to be a Xamarin issue. I have made the following changes to my code"
The relevant changes are in the setter for SelectedFrame:
public string SelectedFrame
{
get { return _selectedFrame; }
set
{
if (_selectedFrame != value)
{
_selectedFrame = value;
if (EnumUtils.ToEnumFromString<FrameType>(_selectedFrame) == FrameType.Road)
{
Directions = DirectionsRoad;
if (Directions.Contains(SelectedDirection))
{
/*Relevant edits*/
var position = Directions.IndexOf(SelectedDirection);
SelectedDirection = Directions[Directions.Count - position -1];
SelectedDirection = Directions[position];
}
else
{
SelectedDirectionIndex = Directions.IndexOf(DirectionType.Right.ToString());
}
}else if (EnumUtils.ToEnumFromString<FrameType>(_selectedFrame) == FrameType.Lane)
{
Directions = DirectionsAll;
/*Relevant edits*/
var position = Directions.IndexOf(SelectedDirection);
SelectedDirection = Directions[Directions.Count - position -1];
SelectedDirection = Directions[position];
}
OnPropertyChanged();
}
}
}
}
It seems that my issue arises when I change the contents of my ObservableCollectoin but the SelectedDirection stays the same.
When I change Directions (which is an ObservableCollection) by assigning it to DirectionsAll (also an ObservableCollection), I need to make sure that the SelectedDirection changes,. The added code ensures that a change actually occurs to SelectionDirection and that fixes it. Seems somewhat hacky but it works.
Outcome:

WPF Binding to behave OneWayToSource and OneTime

Is it possible for a control binding to behave as OneWayToSource and OneTime?
Here is some background: I have a data grid. Each row has text cells and a checkbox. If the checkbox is selected the data from the row will be saved. Now, when user starts typing in any text cell I change the IsChecked property in my ViewModel so the checkbox gets checked. I would like this to happen only once. So, for example, if a user starts typing and decides to uncheck the checkbox I don't want to change it when the user will start typing value again.
Sounds for me like setting binding to both OneWayToSource and OneTime should be a solution but I know binding mode can be set only to a single value. I've been searching for some suggestions and possible workarounds to achieve similar result but with no result.
From msdn:
OneTime updates the target property only when the application starts
or when the DataContext undergoes a change
That means that using a combination of OneWayToSource and OneTime would not solve your issue as the 'one time'-update does not trigger the moment the property changes the first time but on application start or datacontext change.
As you bound your text cell text to some property you can control in that property if IsChecked should be set or not.
private string text_ = "";
private bool isChecked_ = false;
private bool autoSetChecked_ = true;
public bool IsChecked
{
get
{
return isChecked_;
}
set
{
if (isChecked_ == value) {
return;
}
// If user manually changes check state assume the user wants to keep that state
// => Disable auto changing.
autoSetChecked_ = false;
isChecked_ = value;
OnPropertyChanged("IsChecked");
}
}
public Text
{
get
{
return text_;
}
set
{
if (text_ == value) {
return;
}
text_ = value;
OnPropertyChanged("Text");
if (autoSetChecked_) {
// Only set is checked if not done ever before.
autoSetChecked_ = false;
IsChecked = true;
}
}
}
Edit: This requires that your IsChecked-Binding is TwoWay so you can change the checkbox from your viewmodel.

RaisePropertyChanged fails to update the UI

I've been working on an application in MVVM Light lately. I have a TextBox in my XAML bound to my UI. I'd like to validate any input and ensure that only numbers are entered. I've tried the following code:
My TextBox:
<TextBox TabIndex="1" Height="23" MinWidth="410" DockPanel.Dock="Left"
HorizontalAlignment="Left"
Text="{Binding Input, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsEnabled}"
AcceptsReturn="False"
local:FocusExtension.IsFocused="{Binding IsFocused}">
And in my ViewModel:
private string input;
public string Input
{
get { return this.input; }
set
{
decimal test;
if(decimal.TryParse(value, out test))
{
this.input = value;
}
else
{
this.input = "";
}
RaisePropertyChanged("Input");
}
}
This fails to update the UI. If I enter "B" and check the debugger, it runs through the setter, but fails to actually update the UI.
Curiously, if I set this.input = "TEST"; in the else block, the UI updates, but, if I attempt to set it to "", string.Empty, or the value of input before the validation, the UI fails to update.
Is this by design? Possibly a bug? Is there something I'm doing wrong?
Edit I mistakenly forgot to include RaisePropertyChanged in my example code. I've updated it. Raising it isn't the problem as I've watched the debugger run all the way through raising it and returning input via the getter.
Way you use strign type property and then convert to decimal, easier to change lik this:
public decimal Input
{
get { return this.input; }
set
{
this.input = value;
RaisePropertyChanged("Input");
}
}
And for validate use IDataErrorInfo (read more: http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx)
What we have done is created a Custom Control, since we use it for a Currency Text Box. I warn you I have no validation that this is a good idea, or falls in line with MVVM model because all manipulation of the control are done in code behind.
In the control on the textbox we have an event on PreviewTextInput that does this
e.Handled = Functions.DoubleConverter(Convert.ToChar(e.Text), ((TextBox)sender).Text.Replace("$", ""));
Then for the function (which isnt perfect, I have a few issues with it still) is:
static public bool DoubleConverter(char c, string str)
{
if (!char.IsDigit(c))
{
if (c == '.' && (str.Contains('.')))
{
return true;
}
else if (c != '.')
{
return true;
}
}
return false;
}
Please use this as a reference, not exactly as is because it is a very crude implementation.

Categories

Resources