我正在使用 WPF 上的 MVVM 模型编写一个简单的程序。基本上,当用户单击一组单选按钮中的一个单选按钮时,它将使用新帐号更新视图模型中的属性。问题是,当我单击另一个按钮时,会为新按钮 IsChecked Binding 调用转换器,然后为上一个按钮 IsChecked 绑定运行转换器(以丢失其检查状态)。
这导致了一个问题,因为新按钮正在使用正确的帐号更新属性的值,然后当旧按钮调用转换器时,它会转换回旧值。我通过向类添加一个静态变量来破解它,如果 IsChecked 属性为假,则只需返回静态变量中的值。有没有人有更好的解决方案来短路转换器呼叫失去其选中状态的盒子。代码如下:
转换器:
class RadioToAccountConverter : IValueConverter
{
static string myValue; //HACK TO MAKE IT WORK
object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return parameter.ToString();
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value)
{
myValue = parameter.ToString(); // Hack to make it work
return parameter.ToString();
}
return myValue; // Hack to make it work
}
}
XAML:
<RadioButton Foreground="HotPink"
Grid.Column="0"
Content="6087721"
Tag="6087721"
IsChecked="{Binding Account, Converter={StaticResource Radio2Value}, Mode=OneWayToSource, ConverterParameter=6087721}">
</RadioButton>
<RadioButton Foreground="HotPink"
Grid.Column="1"
Content="BFSC120"
IsChecked="{Binding Account, Converter={StaticResource Radio2Value}, Mode=OneWayToSource, ConverterParameter='BFSC120'}">
</RadioButton>
<RadioButton Foreground="HotPink"
Grid.Column="2"
Content="BFSC121"
IsChecked="{Binding Account, Converter={StaticResource Radio2Value}, Mode=OneWayToSource, ConverterParameter=BFSC121}">
</RadioButton>
<RadioButton Foreground="HotPink"
Grid.Column="3"
Content="BFSC206"
IsChecked="{Binding Account, Converter={StaticResource Radio2Value}, Mode=OneWayToSource, ConverterParameter=BFSC206}">
</RadioButton>
财产:
public const string AccountPropertyName = "Account";
private string _account;
/// <summary>
/// Sets and gets the Account property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string Account
{
get
{
return _account;
}
set
{
if (_account == value)
{
return;
}
RaisePropertyChanging(AccountPropertyName);
_account = value;
RaisePropertyChanged(AccountPropertyName);
}
}
任何帮助是极大的赞赏。