Xaml字符串格式化和静态字符串

10

我想知道是否有一种方法可以将日期时间 字符串格式 和静态字符串组合起来。

目前,我可以按照以下方式格式化我的日期,并添加前缀文本:

<TextBlock Text="{Binding MyDate StringFormat=Started {0:dd-MMM-yyyy HH:mm}}"

导致这个结果:

Started 01-Jan-2011 12:00

过去我曾经使用静态字符串来保持日期的通用格式,就像这样(注意没有前缀文本):

<TextBlock Text="{Binding MyDate, StringFormat={x:Static i:Format.DateTime}}" />

这里的i:Format是一个静态类,其中有一个静态属性DateTime,它返回字符串"dd-MMM-yyyy HH:mm"

那么我的问题是:是否有一种方法可以将这些方法组合起来,以便我可以为我的日期添加前缀并使用公共的静态字符串格式化程序?

2个回答

2
您可以使用类似于此的内容来替换绑定(Binding):
public class DateTimeFormattedBinding : Binding {
    private string customStringFormat = "%date%";

    public DateTimeFormattedBinding () {
        this.StringFormat = Format.DateTime;
    }

    public DateTimeFormattedBinding (string path)
        : base(path) {
        this.StringFormat = Format.DateTime;
    }

    public string CustomStringFormat {
        get {
            return this.customStringFormat;
        }
        set {
            if (this.customStringFormat != value) {
                this.customStringFormat = value;
                if (!string.IsNullOrEmpty(this.customStringFormat)) {
                    this.StringFormat = this.customStringFormat.Replace("%date%", Format.DateTime);
                }
                else {
                    this.StringFormat = string.Empty;
                }
            }
        }
    }
}

然后像这样使用它:{local:DateTimeFormattedBinding MyDate, CustomStringFormat=Started %date%}

你可能也可以将替换变得更通用,通过不同的属性(或多个属性)设置。


如果您想填充值和值的格式,我认为这是唯一的选择。我尝试过string.Format("Started {0:{1}}", DateTime.Now, "dd-MMM-yyyy HH:mm"),但抛出了异常。 - Josh G

1
你可以使用像这样的转换器:
<TextBlock>
    <TextBlock.Text>
                <MultiBinding Converter="{StaticResource StringFormatConcatenator}">
                        <Binding Source="Started {0}"/>
                        <Binding Source="{x:Static i:Format.DateTime}"/>                                        
                        <Binding Path="MyDate"/>
                </MultiBinding>
    </TextBlock.Text>
</TextBlock>

public class StringFormatConcatenator : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string format = values[0].ToString();
        for (int i = 0; i < (values.Length - 1) / 2; i++)
            format = format.Replace("{" + i.ToString() + "}", "{" + i.ToString() + ":" + values[(i * 2) + 1].ToString() + "}");

        return string.Format(format, values.Skip(1).Select((s, i) => new { j = i + 1, s }).Where(t => t.j % 2 == 0).Select(t => t.s).ToArray());
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        return new string[] { };
    }
}

您可以按照格式 (格式,值) 的配对方式添加所需的变量。
其中:
绑定 0:完整的格式,不包含特定变量格式({0:dd-MMM-yyyy HH:mm} 替换为 {0})。
奇数绑定(1、3、5...):变量特定格式("dd-MMM-yyyy HH:mm")。
偶数绑定(2、4、6...):变量值(MyDate)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接