假设我有以下代码:
<ContextMenu IsEnabled="{Binding Converter={StaticResource SomeConverterWithSmartLogic}}">
所以,除了 Converter 之外,我没有指定任何绑定信息……是否可以强制 WPF 只调用一次?
UPD:此时我将值转换器的状态存储在静态字段中
假设我有以下代码:
<ContextMenu IsEnabled="{Binding Converter={StaticResource SomeConverterWithSmartLogic}}">
所以,除了 Converter 之外,我没有指定任何绑定信息……是否可以强制 WPF 只调用一次?
UPD:此时我将值转换器的状态存储在静态字段中
您是否尝试将绑定设置为一次性?
如果您的转换器应该转换一次,那么您可以将您的转换器编写成这样,如果这不会引起其他干扰,至少不需要静态字段等,例如
[ValueConversion(typeof(double), typeof(double))]
public class DivisionConverter : IValueConverter
{
double? output; // Where the converted output will be stored if the converter is run.
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (output.HasValue) return output.Value; // If the converter has been called
// 'output' will have a value which
// then will be returned.
else
{
double input = (double)value;
double divisor = (double)parameter;
if (divisor > 0)
{
output = input / divisor; // Here the output field is set for the first
// and last time
return output.Value;
}
else return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}