Xaml StringFormat 和静态字符串 [英] Xaml StringFormat and static strings

查看:37
本文介绍了Xaml StringFormat 和静态字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看有没有办法将日期时间字符串格式和静态字符串结合起来.

I want to see if theres a way to combine datetime string format and static strings.

所以目前我可以用这样的文本格式化我的日期和前缀:

So currently I can format my date and prefix with text like this:

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

结果如下:

Started 01-Jan-2011 12:00

过去,我可以使用静态字符串来为我的日期保留通用格式;像这样(注意没有前缀文本):

In the past I've been able to use a static string to keep a common format for my dates; like this (Note no prefixed text):

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

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

Where i:Format is a static class with a static property DateTime that returns the string "dd-MMM-yyyy HH:mm"

所以我在问什么;有没有办法组合这些方法,以便我可以为日期添加前缀并使用通用静态字符串格式化程序?

So what I'm asking; is there a way to combine these methods so that I can prefix my date and use the common static string formatter?

推荐答案

你可以使用这样的东西来代替 Binding:

You could use something like this in place of the 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%} 一样使用它

您也可以将替换设为通用,并通过不同的属性(或多个属性)进行设置.

You could probably make the replacement generic also, and set it via a different property (or properties).

这篇关于Xaml StringFormat 和静态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆