我在同时打开的两个窗口中使用以下控件模板,并且都使用相同的 View 模型。
这是模板;
<ControlTemplate x:Key="SecurityTypeSelectionTemplate">
<StackPanel>
<RadioButton GroupName ="SecurityType" Content="Equity"
IsChecked="{Binding Path=SecurityType, Mode=TwoWay, Converter={StaticResource EnumBoolConverter}, ConverterParameter=Equity}" />
<RadioButton GroupName ="SecurityType" Content="Fixed Income"
IsChecked="{Binding Path=SecurityType, Mode=TwoWay, Converter={StaticResource EnumBoolConverter}, ConverterParameter=FixedIncome}" />
<RadioButton GroupName ="SecurityType" Content="Futures"
IsChecked="{Binding Path=SecurityType, Mode=TwoWay, Converter={StaticResource EnumBoolConverter}, ConverterParameter=Futures}" />
</StackPanel>
</ControlTemplate>
这是 View 模型属性:
private SecurityTypeEnum _securityType;
public SecurityTypeEnum SecurityType
{
get { return _securityType; }
set
{
_securityType = value; RaisePropertyChanged("SecurityType");
}
}
这是枚举:
public enum SecurityType { Equity, FixedIncome, Futures }
这是转换器:
public class EnumToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object enumTarget, CultureInfo culture)
{
string enumTargetStr = enumTarget as string;
if (string.IsNullOrEmpty(enumTargetStr))
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object expectedEnum = Enum.Parse(value.GetType(), enumTargetStr);
return expectedEnum.Equals(value);
}
public object ConvertBack(object value, Type targetType, object enumTarget, CultureInfo culture)
{
string expectedEnumStr = enumTarget as string;
if (expectedEnumStr == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, expectedEnumStr);
}
}
问题有点奇怪。我有两个窗口显示 SAME ViewModel 的 View 略有不同。上面显示的相同模板在两个 View 中重复使用。
如果 Equity 最初设置为 SecurityType,我可以通过单击相关单选按钮将其更改为 FixedIncome。然后我无法将其更改回股权。
但是,我可以将其设置为 future 。但在那之后,我无法通过单击相关单选按钮将其更改为 FixedIncome 或 Equity。
在我无法设置更改的情况下发生的情况是 Setter 被调用了两次。第一次将值设置为正确的选定值,但在触发 RaisePropertyChanged 的那一刻,
再次调用 setter,这次使用原始值。
感觉就像当 RaisePropertyChanged 时,setter 被第二个窗口的绑定(bind)调用,从而覆盖了用户进行选择的第一个窗口中设置的值。
有谁知道这是否是这种情况以及在这种情况下如何避免?
最佳答案
这是我的 EnumToBoolConverter 版本:
public class EnumToBoolConverter : BaseConverterMarkupExtension<object, bool>
{
public override bool Convert(object value, Type targetType, object parameter)
{
if (value == null)
return false;
return value.Equals(Enum.Parse(value.GetType(), (string)parameter, true));
}
public override object ConvertBack(bool value, Type targetType, object parameter)
{
return value.Equals(false) ? DependencyProperty.UnsetValue : parameter;
}
}
关于c# - 使用相同的 ViewModel 打开两个窗口时无法设置单选按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098611/