gpt4 book ai didi

Silverlight:绑定(bind)到静态值

转载 作者:行者123 更新时间:2023-12-04 02:31:30 24 4
gpt4 key购买 nike

我需要从翻译管理器中检索 TextBlock.Text,例如

<TextBlock Text="{Binding TranslateManager.Translate('word')}" />

我不想为所有文本 block 设置 DataSource。我发现如何做到这一点的唯一方法是绑定(bind)到“静态”类并使用转换器:
<TextBlock Text="{Binding Value, 
Source={StaticResource Translation},
Converter={StaticResource Translation},
ConverterParameter=NewProject}" />

而这些助手类
 public class TranslationManager : IValueConverter
{
public static string Translate(string word)
{
return translate(word);
}

// this is dummy for fake static binding
public string Value { get; set; }

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var name = parameter as string;
return TranslationManager.Translate(name, name);
}
}

但是,有没有更好——更短——的方式?

最佳答案

让我先声明:您应该使用静态资源来翻译单词:Application Resources*.RESX Files

但是,如果您需要简化您的 xaml,您唯一缺少的就是在整个 View 上放置一个数据上下文。听起来您没有使用 MVVM,因此将此逻辑放在构造函数或后面的代码中,您可以通过绑定(bind)访问更多功能:

public MainPage()
{
// Required to initialize variables
InitializeComponent();


// This is the key to simplify your xaml,
// you won't have set the source for individual controls
// unless you want to
DataContext = this;
}

然后,在您的 xaml 中,您的文本框可以简化为:
<TextBlock Text="{Binding 
ConverterParameter=Hi,
Converter={StaticResource Translator}}"/>

我的翻译:
public class Translator : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return "Hola!";
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return "Hi!";
}
}

关于Silverlight:绑定(bind)到静态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2653169/

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