是否可以在转换器参数中使用来自IValueConverter的静态值?
问题描述:
在Silverlight中,我有一个标准的IValueConverter,我想将可能的参数定义为常量字符串。是否可以在转换器参数中使用来自IValueConverter的静态值?
public class BooleanConverter : IValueConverter
{
public const string PARAMETER_ONE = "one";
public const string PARAMETER_TWO = "two";
...
话,我想用不断的转换参数内,是这样的:
<TextBlock Text="{Binding Name, Converter={StaticResource BooleanConverter},
ConverterParameter={StaticResource BooleanConvereter.PARAMETER_TWO}" />
这可能吗?如果是,那么正确的语法是什么?
答
您可以同时使用参数和参数。示例:
<converters:VisibilityConverter x:Key="inversVisibConverter" Inverse="True"/>
Visibility="{Binding ABoolValue, Mode=OneWay, Converter={StaticResource inversVisibConverter},ConverterParameter=abc}"
转换器(同时包含参数和参数):
public sealed class VisibilityConverter : IValueConverter {
public bool Inverse { get; set; }
#region Implementation of IValueConverter
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Visibility visibility = Visibility.Visible;
if (value is bool)
{
visibility = (bool) value ? Visibility.Visible : Visibility.Collapsed;
}
if(parameter != null)
{
//handle parameter here:
}
if (Inverse)
{
visibility = (visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
}
return visibility;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if (!(value is Visibility)) {
throw new ArgumentOutOfRangeException("value", "VisibilityConverter can only convert from Visibility");
}
if (targetType == typeof(bool)) {
return ((Visibility)value == Visibility.Visible) ? true : false;
}
throw new ArgumentOutOfRangeException("targetType", "VisibilityConverter can only convert to Boolean");
}
#endregion
}
答
您应该能够使用静态标记扩展:
<TextBlock Text="{Binding Name,Converter={StaticResource BooleanConverter},ConverterParameter={x:Static cnv:BooleanConverter.PARAMETER_ONE}}" />
注意,x:Static
需要类本身,而不是你的资源的引用。因此,您需要为其添加适当的XML名称空间前缀。
+0
我应该提到,我在Silverlight我的工作,我做了标记,但忘了说在文中。从我所看到的,{x:Static}仅适用于WPF。那是对的吗? – fergie
虽然我更喜欢使用参数,但您的解决方案很有趣,如果使用该属性并将其链接到枚举,则可以解决我的问题。然后我只能使用定义的枚举值。谢谢! – fergie