2011-04-08 5 views
9

날짜 형식 문자열 형식과 정적 문자열을 결합하는 방법을보고 싶습니다. 과거에는Xaml StringFormat 및 정적 문자열

Started 01-Jan-2011 12:00 

나는에 정적 문자열을 사용 할 수있었습니다 :이의

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

결과 :

그래서 현재 나는이 같은 텍스트로 내 날짜와 접두사를 포맷 할 수 있습니다 내 날짜에 대한 공통 형식 유지. 이런 식으로 (더 접두사 텍스트 유의하십시오) : i:Format 문자열 "dd-MMM-yyyy HH:mm"

그래서

내가 부탁 해요 무엇을 반환하는 정적 속성 DateTime와 정적 클래스입니다

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

을; 거기에 내 날짜를 접두사 및 일반적인 정적 문자열 포맷터를 사용할 수 있도록 이러한 방법을 결합하는 방법은 무엇입니까? 당신은 아마 일반적인 또한 교환을하고, 다른 속성을 통해 설정할 수 {local:DateTimeFormattedBinding MyDate, CustomStringFormat=Started %date%}

처럼 사용 다음

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

(또는 :

답변

1

당신은 바인딩 대신이 같은 것을 사용할 수 있습니다 속성).

+0

난 당신이 가치와 값의 형식을 모두 채우려면이 유일한 대안이라고 생각합니다. 나는 string.Format ("{0 : {1}}"DateTime.Now, "dd-MMM-yyyy HH : mm")'을 시도하고 예외가 발생했습니다. –

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 바인딩을 :

Binding odd (1,3,5 ...) : 변수 형식 ("dd-MMM-yyyy HH : mm"을 {0}으로 대체) MMM-yyyy HH : mm ")

바인딩도 (2,4,6 ...) : 변수 값 (MyDate가)