I got a strange behaviour if I want to update my UI by RaisePropertyChanged. I use the 2nd solution (by Johnathan1) of this post: I implemented the RadioBoolToIntConverter.
My VM looks like this:
public int myFilterRadioButtonInt
{
get
{
return _Filter.FilterMyProperty ? 1 : 2;
}
set
{
if (value == 1)
_Filter.FilterMyProperty = true;
else if (value == 2)
_Filter.FilterMyProperty = false;
else
return;
RaisePropertyChanged("myFilterRadioButtonInt");
}
}
Converter looks like this (by Jonathan1 of this post):
public class RadioBoolToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int integer = (int)value;
if (integer==int.Parse(parameter.ToString()))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
For understanding _Filter.FilterMyProperty
is a bool value of the model which is responsible if my value which will be filtered is shown or is not shown. This is binded to 2 RadioButtons using the RadioBoolToIntConverter:
<RadioButton IsChecked="{Binding Path=myFilterRadioButtonInt, Converter={StaticResource RadioBoolToIntConverter}, ConverterParameter=1}">Show</RadioButton>
<RadioButton IsChecked="{Binding Path=myFilterRadioButtonInt, Converter={StaticResource RadioBoolToIntConverter}, ConverterParameter=2}">Don't show</RadioButton>
Binding and toggling the RadioButtons is working properly.
The problem is if I set _Filter.FilterMyProperty = true
by code (set a standard filter where this value should be filtered) and then do RaisePropertyChanged("myFilterRadioButtonInt")
the _Filter.FilterMyProperty
will be set to false
.
Edit:
By RaisePropertyChanged("myFilterRadioButtonInt")
(called by the setter of the Filter Property in the VM) the setter of myFilterRadioButtonInt
is called again and it will set the current value of the RadioBox (in my case the value
is 2
so the setter will set back the _Filter.FilterMyProperty
to false
.
It is not possible to change the value of the RadioBoxes by code with this method. I thought only the getter will be called when I call RaisePropertyChanged("myFilterRadioButtonInt")
.
How can I solve this problem and why is the setter being called by RaisePropertyChanged("myFilterRadioButtonInt")
?
Edit:
Returning the parameter in ConvertBack() was the problem. Here is my solution:
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool val;
if (!bool.TryParse(value.ToString(), out val))
return 0;
int iParam;
if (!int.TryParse(parameter.ToString(), out iParam))
return 0;
return val ? iParam : 0;
}