在Silverlight中,我有一个标准的IValueConverter,我想将可能的参数定义为const字符串。
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}" />
这可能吗?如果是,那么正确的语法是什么?
答案 0 :(得分:2)
您应该能够使用静态标记扩展名:
<TextBlock Text="{Binding Name,Converter={StaticResource BooleanConverter},ConverterParameter={x:Static cnv:BooleanConverter.PARAMETER_ONE}}" />
请注意,x:Static
需要引用类本身,而不是您的资源。因此,您需要在其前面添加适当的XML名称空间前缀。
答案 1 :(得分:1)
您可以同时使用参数和参数。样品:
<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
}