如何从 XAML x:Array 中的 ViewModel 访问常量字符串



我正在使用一个转换器,我想为其传递 2 个转换器参数。我在转换器中有静态字符串,但我无法访问它。

问题陈述

想要访问 XAML x:Array 中的public static string STAR = "STAR";

XAML:

<UserControl.Resources>
<local:CustomGridLengthConverter x:Key="CustomGridLengthConverter"/>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition>
<ColumnDefinition.Width>
<Binding Path="CustomLength" Converter="{StaticResource CustomGridLengthConverter}">
<Binding.ConverterParameter>
<x:Array Type="{x:Type system:String}">
<system:String>AUTO</system:String>-->Working
<system:String>STAR</system:String>-->Working
<!--<local:CustomGridLengthConverter.STAR/>--> *NOT* Working
</x:Array>
</Binding.ConverterParameter>
</Binding>
</ColumnDefinition.Width>
</ColumnDefinition>
</Grid.ColumnDefinitions>

转换器代码:

public class CustomGridLengthConverter : IValueConverter
{
public static string ABSOLUTE = "ABSOLUTE";
public static string AUTO= "AUTO";
public static string STAR = "STAR";
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double tempGridLengthVal = 0.0;
//do necessary null/datatype check
string[] params=parameter as string[];
// use default value when 'value' is null
string defaultValue=params[0];
//use this value to specify if user wants absolute value or relative value.
string convertTo=params[1];
if (value.IsNotNull() && Double.TryParse(value.ToString(), out 
tempGridLengthVal))
{
//If given value is parsable, create new GridLength with this value
gridLength = new GridLength(tempGridLengthVal);
//User can specify if they want to use the given value as exact 
value or as a star percentage
if (convertTo.Equals(STAR))
gridLength = new GridLength(tempGridLengthVal,GridUnitType.Star);
} 
}

编辑:这是一个与"另一个问题"不同的用例,因为该问题值被分配给依赖对象,而我没有依赖对象,我只想将静态字符串值传递给数组。

谢谢

RDV

您可以使用x:Static标记扩展:

<Binding.ConverterParameter>
<x:Array Type="{x:Type system:String}">
<system:String>AUTO</system:String>
<system:String>STAR</system:String>
<x:Static Member="local:CustomGridLengthConverter.STAR" />
</x:Array>
</Binding.ConverterParameter>

最新更新