2012-10-31 56 views
1

我不是那個用MVVM的公司,我希望有人能幫助我。我使用C#/ XAML爲Windows Phone的8 通常我的視圖模型提供了一個myProperty的屬性,我會結合這樣的: 如何在ViewModel中使用數據綁定屬性而不使用本地化字符串?

<TextBlock Text="{Binding MyProperty, StringFormat='This Property: {0}'}" FontSize="30" /> 

的問題是,在我看來模型中,有一些數據綁定由不同字符串定位的屬性。例如。假設你有一個約會 - 即將到來或已過時。這個日期應該是這樣的本地化:

upcoming: "The selected date {0:d} is in the future" 
passed: "The selected date {0:d} already passed" 

是否可以在XAML中進行本地化?或者還有其他可能性來避免視圖模型中的本地化字符串? (畢竟是避免視圖模型中的本地化字符串?)

在此先感謝!

問候, 馬克

回答

0

嘗試使用IValueConverter

例子:

的XAML:

<Window x:Class="ConverterSpike.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ConverterSpike="clr-namespace:ConverterSpike" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <ConverterSpike:DateStringConverter x:Key="DateConverter" /> 
    </Window.Resources> 
    <Grid> 
     <TextBlock Text="{Binding MyProperty, Converter={StaticResource DateConverter}}" /> 
    </Grid> 
</Window> 

轉換器:

using System; 
using System.Globalization; 
using System.Windows.Data; 

namespace ConverterSpike 
{ 
    public class DateStringConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      if (value == null) return string.Empty; 
      var date = value as string; 
      if (string.IsNullOrWhiteSpace(date)) return string.Empty; 

      var formattedString = string.Empty; //Convert to DateTime, Check past or furture date, apply string format 

      return formattedString; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 
+0

謝謝!這似乎很有希望! –

+0

到目前爲止效果很好! –

0

如果你正在尋找指定的XAML中的固定格式,但它對於像日期支持格式字符串。例如,對於DMY,使用StringFormat = {0:'dd/MM/yyyy'}。它也支持一些預定義的格式。只需在xaml綁定中搜索「日期格式」即可獲取詳細信息。

0

您可以創建本地化resorce文件:

String.xaml

<system:String x:Key="MyKey">English {0} {1}</system:String> 

String.de-DE.xaml

<system:String x:Key="MyKey">{0} Deutsch {1}</system:String> 

,比你的意見通過密鑰使用字符串。如果你需要的佔位符,你可以用multibinding這樣填補他們:

<TextBlock> 
    <TextBlock.Text> 
     <MultiBinding StringFormat="{StaticResource MyKey}"> 
      <Binding Path="MyObject.Property1" /> 
      <Binding Path="MyObject.Property2" /> 
     </MultiBinding> 
    </TextBlock.Text> 
</TextBlock> 

如果MyObject.Property1是「text1」中和MyObject.Property2是「文本2」,導致英語將是「英語文本1文本2」和德國 「文本1德語文本2」

+0

不幸的是MultiBinding不可用的Windows Phone =/ –

相關問題