gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:34:22 25 4
gpt4 key购买 nike

我想在我的 WP7 应用程序中使用从 Web 服务获取的静态文本。每个文本都有一个名称(标识符)和一个内容属性。

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

Name = "M43";
Content = "This is the text to be shown";

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

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

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

然后在 XAML 中:

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

...

<TextBlock Text="{Binding 'M43', Converter={StaticResource StaticTextConverter}}"/>

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

有人有什么建议吗?

最佳答案

我终于找到了答案。答案是@Shawn Kendrot 的答案和我在这里问的另一个问题的混合:IValueConverter not getting invoked in some scenarios

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

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

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

由于文本的ID是用converter参数传入的,所以converter看起来差不多:

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

但是,事实证明,如果它DataContext,则不会调用绑定(bind)和转换器。要解决此问题,只需将控件的 DataContext 属性设置为任意值即可:

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

然后一切都按预期进行!

关于c# - 如何在 XAML 中将静态值传递给 IValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11796930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com