如何在XAML中将静态值传递给IValueConverter

Zap*_*pel 10 c# xaml ivalueconverter windows-phone-7

我想在我的WP7应用程序中使用从Web服务获取的静态文本.每个文本都有一个名称(indetifier)和一个Content属性.

例如,文本可能如下所示:

Name = "M43";
Content = "This is the text to be shown";
Run Code Online (Sandbox Code Playgroud)

然后我想将文本的名称(即标识符)传递给a IValueConverter,然后查找Name并返回文本.

我认为转换器看起来像这样:

public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(value)).Content;
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在XAML中:

<phone:PhoneApplicationPage.Resources>
    <Helpers:StaticTextConverter x:Name="StaticTextConverter" />
</phone:PhoneApplicationPage.Resources>

...

<TextBlock Text="{Binding 'M43', Converter={StaticResource StaticTextConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

但是,这似乎不起作用,我不确定我是否正确地将值传递给转换器.

有人有什么建议吗?

Zap*_*pel 13

我终于找到了答案.答案是@Shawn Kendrot和我在这里问的另一个问题之间的混合:IValueConverter在某些情况下没有被调用

总结使用IValueConverter我必须在以下庄园中绑定我的控件的解决方案:

<phone:PhoneApplicationPage.Resources>
    <Helpers:StaticTextConverter x:Name="TextConverter" />
</phone:PhoneApplicationPage.Resources>

<TextBlock Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />
Run Code Online (Sandbox Code Playgroud)

由于使用转换器参数传入文本的ID,因此转换器看起来几乎相同:

public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null && parameter is string)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(parameter)).Content;
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,事实证明,如果没有 a,则不会调用绑定和转换器DataContext.要解决这个问题,DataContext控件的属性必须设置为任意的:

<TextBlock DataContext="arbitrary" 
           Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />
Run Code Online (Sandbox Code Playgroud)

然后一切都按预期工作!


Arc*_*rus 7

问题在于你的绑定。它会检查DataContext,这个对象上,它会尝试评估的属性M62ValueboxConsent该对象上。

您可能希望在应用程序中的某个位置添加静态键,您可以绑定到:

<TextBlock Text="{Binding Source="{x:Static M62.ValueboxConsent}", Converter={StaticResource StaticTextConverter}}" />
Run Code Online (Sandbox Code Playgroud)

M62 是一个静态类,您的密钥所在的位置.. 像这样:

public static class M62
{
    public static string ValueboxConsent
    {
        get { return "myValueBoxConsentKey"; }
    }
}
Run Code Online (Sandbox Code Playgroud)