繁体   English   中英

WPF中用于绑定文本的字符串格式

[英]String format for binding text in WPF

说我有一个静态文本资源

public static string MainText = "Test: {0} Test2: {1}";

然后我想像这样在WPF中使用此文本

<Label Content="x:Static ***.MainText" />

但是将两个值绑定到它,我该怎么做?

您可以通过以下两种方式实现此目的,一种是使用转换器,另一种是不使用转换器。

绑定中的“ Text1”和“ Text2”是DataContext的属性。

您需要将“ MainText”更改为属性:

public static string MainText { get; set; } = "Test: {0} Test2: {1}";

没有转换器:

<Label>
    <Label.Content>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{x:Static local:MainWindow.MainText}">
                    <Binding Path="Text1" />
                    <Binding Path="Text2" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Label.Content>
</Label>

使用转换器:

<Label>
    <Label.Resources>
        <local:TextFormatConverter x:Key="TextFormatConverter" />
    </Label.Resources>
    <Label.Content>
        <MultiBinding Converter="{StaticResource TextFormatConverter}" ConverterParameter="{x:Static local:MainWindow.MainText}">
            <Binding Path="Text1" />
            <Binding Path="Text2" />
        </MultiBinding>
    </Label.Content>
</Label>

和转换器:

public class TextFormatConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string fmt = parameter as string;
        if (!string.IsNullOrWhiteSpace(fmt))
            return string.Format(fmt, values);
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM