2011-04-08 21 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)