【发布时间】:2014-12-30 02:30:19
【问题描述】:
如果我想通过 RaisePropertyChanged 更新我的 UI,我会遇到一个奇怪的行为。 我使用this post 的第二个解决方案(Johnathan1):我实现了 RadioBoolToIntConverter。
我的虚拟机如下所示:
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:
<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>
绑定和切换 RadioButtons 工作正常。
问题是如果我通过代码设置_Filter.FilterMyProperty = true(设置一个标准过滤器来过滤这个值)然后做RaisePropertyChanged("myFilterRadioButtonInt")_Filter.FilterMyProperty将被设置为false。
编辑:
RaisePropertyChanged("myFilterRadioButtonInt")(由 VM 中 Filter 属性的设置器调用)再次调用 myFilterRadioButtonInt 的设置器,它将设置 RadioBox 的当前值(在我的情况下,value 是 @987654334 @ 所以setter会将_Filter.FilterMyProperty设置回false。
使用此方法无法通过代码更改 RadioBoxes 的值。我以为当我调用RaisePropertyChanged("myFilterRadioButtonInt") 时只会调用getter。
我该如何解决这个问题,为什么 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 的值。发布转换器。我敢打赌转换器正在改变价值。
-
@Blam 将转换器添加到问题中。
-
通常只调用getter,否则(如果调用setter)会有一些StackOverflow异常,显然有调用
RaisePropertyChanged在设置器中。所以我怀疑还有其他一些代码触发了setter,而不是RaisePropertyChanged()。
标签: c# wpf xaml mvvm data-binding