如果我想通过RaisePropertyChanged更新我的UI,我得到了一个奇怪的行为。 我使用this post的第二个解决方案(by Johnathan1):我实现了RadioBoolToIntConverter。RaisePropertyChanged设置回单选按钮的值
我的虚拟机看起来是这样的:
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");
}
}
转换器看起来像这样(由this post Jonathan1):
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;
}
}
对于理解_Filter.FilterMyProperty
是模型的一个布尔值,它是负责的,如果我的显示或未显示将被过滤的值。这是绑定使用RadioBoolToIntConverter 2个单选按钮:
<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>
绑定和切换的单选按钮是否工作正常。
问题是如果我设置由代码_Filter.FilterMyProperty = true
(设定一个标准过滤器,其中这个值应该被过滤),然后执行所述RaisePropertyChanged("myFilterRadioButtonInt")
_Filter.FilterMyProperty
将被设置为false
。
编辑:
通过RaisePropertyChanged("myFilterRadioButtonInt")
(由VM中的筛选器属性设置者的称呼)的myFilterRadioButtonInt
设置器再次调用,它将设置RadioBox的电流值(在我的情况下value
被2
所以setter方法折戟_Filter.FilterMyProperty
到false
。
这是不可能通过代码用这种方法来改变选项框的值。我想,当我打电话RaisePropertyChanged("myFilterRadioButtonInt")
只,吸气将被调用。 我该如何解决这个问题,为什么通过RaisePropertyChanged("myFilterRadioButtonInt")
调用setter?
编辑:
返回在ConvertBack参数()是问题所在。这里是我的解决方案:
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;
}
RaisePropertyChanged( “myFilterRadioButtonInt”);不会改变_Filter.FilterMyProperty的值。张贴转换器。我敢打赌,转换器正在改变价值。 – Paparazzi 2014-11-03 13:41:14
@Blam添加转换器的问题。 – RodMcKay 2014-11-03 14:21:28
通常只调用getter,否则(如果调用者被调用)将会出现一些*** StackOverflow ***异常,显然在setter中调用了'RaisePropertyChanged'。所以我怀疑还有其他一些代码触发setter,而不是'RaisePropertyChanged()'。 – 2014-11-03 15:28:44