在XAML中使用静态函数绑定

本文关键字:静态函数 绑定 XAML | 更新日期: 2023-09-27 18:15:06

我有一个XAML文件,我想用变量替换字段名,这样我就可以为我的应用程序提供更多语言的翻译支持。

我目前在我的应用程序中使用翻译的方式类似于translate .getString("stringname") (translation是一个静态类,具有静态getString函数,从资源文件中获取翻译后的字符串)

现在对于xaml部分,我有这样的内容:

<TextBlock Text="Some string for translation" VerticalAlignment="Center"/>

我可以这样做:

代码:

var translatedString = Translation.getString("stringname")
Xaml:

<TextBlock Text="{Binding translatedString}" VerticalAlignment="Center"/>

但是这是非常丑陋和冗长的。我能以某种方式直接从xaml访问函数吗?

:

<TextBlock Text="{CustomBinding stringname}" VerticalAlignment="Center"/>

在我的项目某处,我分配使用"CustomBinding bla"将运行它作为一个函数translate . getstring("bla"),并使用返回的字符串为我想要的翻译效果。

这可能吗?

是否有其他的"业务标准",通常是这样做的?

在XAML中使用静态函数绑定

您可以通过创建自定义 MarkupExtension 并使用它来代替Binding。

public class TranslateString : MarkupExtension
{
    public string Value { get; set; }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (String.IsNullOrWhiteSpace(Value))
            return Value;
        return Translation.getString(Value);
    }
}
现在,您可以在XAML中像这样使用它:
<TextBlock Text="{local:TranslateString Value='Some string for translation'}"/>
当然你必须在根级定义命名空间 local ,像这样:
xmlns:local="clr-namespace:WpfApplication1"

WpfApplication1替换为TranslateString类的实际名称空间

我已经这样实现了:

public partial class App : Application
{
    Dictionary<string, string> localizer;
    public App()
    {
        localizer = new Dictionary<string, string>() { { "loc", "locdsasdasd" } };
        //LoadLocalizer(); 
        this.Resources.Add("Localizer", localizer);
    }
}

LocBinding.cs

 using System;
 using System.Windows.Data;
 using System.Collections.Generic;
namespace Stackoverflow
{
public class LocBinding : Binding
{
    static Dictionary<string, string> localizer=((Dictionary<string,string>)   
     (App.Current.Resources["Localizer"]));
    public LocBinding(string property)
    {
        if (string.IsNullOrWhiteSpace(property))
            throw new ArgumentNullException("binding path is null");
        string value;
        if (localizer.TryGetValue(property, out value))
            this.Source = value;
        else
            throw new KeyNotFoundException(property + "key is not defined in       
            localizer");
    }
}
}

.xaml.cs

<Window x:Class="Stackoverflow.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Stackoverflow"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Label Content="{local:LocBinding loc}"/>
</Grid>

本地化器中的这个值只是用于测试,但实际上这些值将从数据库或xml或.resx文件中填充。

据我所知,这类问题没有商业标准。

如果说XAML有什么是真的,那就是它太啰嗦了。这并不总是一件坏事,但这意味着即使是带有简单自定义行为的控件也可能很棘手。

有一个全球化应用程序的推荐工作流,但它很复杂,我不骗你,它实际上包括使用和修改微软提供的示例应用程序的说明,作为工作流的一部分。

另一种选择是像往常一样进行开发,并使用Sisulizer之类的工具来代理本地化。当然,这更容易,但要花钱。

使用任何一个工作流,您可以在Application.Resources中定义字符串并将它们引用为DynamicResource