在某些情况下未调用 IValueConverter [英] IValueConverter not getting invoked in some scenarios

查看:43
本文介绍了在某些情况下未调用 IValueConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用从网络服务获取的文本集合,这些文本应该用于各种控件.

I am using a collection of texts fetched from a web service, which should be used for a variety of controls.

在我看来,最简单和最动态的方法是使用 IValueConverter 来获取给定的文本,如下所示:

The easiest and most dynamic way to do this, in my opinion, is to use an IValueConverter to get the given text as follows:

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;
    }
}

然后在 XAML 中,我将文本的 ID(名称")提供给转换器:

And then in the XAML I give the ID of the text ('Name') to the converter:

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

<TextBlock Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />

然后要更改某个控件的文本,只需更改参数中的 ID 或从某个 Web 界面更改文本本身即可.

Then to change the text of some control, all that has to be done is to either change the ID in the parameter or change the text itself from some web interface.

只有在设置了 ItemSource 的某种 DataTemplate 上下文中才调用值转换器,就像 Binding 属性只在那里工作.

That the value converter only gets invoked when in some sort of DataTemplate context where the ItemSource has been set, as if the Binding property only works there.

每当我在其他任何地方使用此方法时,都不会调用值转换器.

Whenever I use this method anywhere else, the value converter is simply not invoked.

有人知道我可能做错了什么吗?

Does anyone have an idea of what I might be doing wrong?

推荐答案

为您的文本块设置 DataContext="object",其中转换器不工作并且将调用值转换器.

Set DataContext="object" for your textblocks where the convertet is not working and the value converter will be invoked.

此解决方法将在您的场景中发挥作用.

This workaround will do the trick in your scenario.

这篇关于在某些情况下未调用 IValueConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆