WPF:突出显示日期的一部分

Veg*_*gar 3 .net c# wpf

我有一个TextBlock,使用当前文化的标准短日期格式显示日期.

String.Format(culture, "{0:d}", someDate)
Run Code Online (Sandbox Code Playgroud)

现在,产品经理希望以粗体突出显示年份.起初,我认为这很容易; 有一次运行绑定到日/月 - 部分,第二次运行到年份部分.

<TextBlock>
  <Run Text="{Binding DayMonthPart}"/>
  <Run FontWeight="Bold" Text="{Binding YearPart}"/>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

但那不会,因为不同的文化有不同的顺序.有些人把年份放在首位,有些人把它放在最后.

那么,我该如何实现呢?
有任何想法吗?

bit*_*onk 6

这是适用于所有文化的通用解决方案:

var r = new Regex(@"^(?<first>[^y]*?)(?<year>y+)(?<second>[^y]*?)$");
var mc = r.Matches(info.DateTimeFormat.ShortDatePattern);
var f = mc[0].Groups["first"].Value;
var y = mc[0].Groups["year"].Value;
var s = mc[0].Groups["second"].Value;

this.First = string.IsNullOrEmpty(f) ? string.Empty : this.date.ToString(f, info);
this.Year = this.date.ToString(y);
try
{
    this.Second = string.IsNullOrEmpty(s) ? string.Empty : this.date.ToString(s, info);           
}
catch
{
    // fallback: sometimes the last char is just a '.'
    this.Second = s;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的XAML中:

<TextBlock>
    <Run Text="{Binding First, Mode=OneWay}" />
    <Run FontWeight="Bold" Text="{Binding Year, Mode=OneWay}" />
    <Run Text="{Binding Second, Mode=OneWay}" />
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

.NET的所有文化