2011-04-08 42 views
9

我想看看是否有一种方法来结合日期时间字符串格式和静态字符串。Xaml StringFormat和静态字符串

所以目前我可以格式化我的日期和前缀文字是这样的:在这个

<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是一个静态类与返回字符串"dd-MMM-yyyy HH:mm"

所以我问什么静态属性DateTime;有没有一种方法来组合这些方法,以便我可以为我的日期加前缀并使用常用的静态字符串格式化程序?

回答

1

你可以使用像这样的地方的绑定:

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%}

你也许可以使更换通用还,并通过不同的属性进行设置(或属性)。

+0

我认为这是唯一的选择,如果你想填补这两个值和值的格式。我尝试过'string.Format(“Started {0:{1}}”,DateTime.Now,“dd-MMM-yyyy HH:mm”)'并且得到一个异常。 – 2011-04-08 12:05:49

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)