2016-07-25 4 views
0

wpfアプリケーションでtextblockを使用して、日付と時刻を表示する文字列プロパティをバインドしています。文字列プロパティにStringFormatを適用して日付の内容をフォーマットする方法はありますか?私は次のようにしましたが、それは仕事量です。助けてください。文字列プロパティをtextblockにバインドしてカスタム日付フォーマットを適用する

モデルではプロパティが

public string alertTimeStamp { get; set; } 

私は

<TextBlock Grid.Row="0" Grid.Column="2" HorizontalAlignment="Right" Margin="25,5,0,0" Text="{Binding alertTimeStamp, StringFormat=0:dd MMM yyyy hh:mm:ss tt}"></TextBlock> 

をしようとしていますビューで、出力はまだ2016年7月25日午前12時20分23秒PMです

+0

これが重複する可能性を試してみてくださいhttp://stackoverflow.com/questions/5584948/format-date-time-in-xaml-in-silverlight –

答えて

0

stringオブジェクトをDateTimeに変更するには、IValueConverterを追加する必要があります。このようなもの。

public class StringToDateValueConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      return DateTime.Parse(value.ToString()); 
     } 
     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

もちろん、検証ロジックのいくつかのフォームを実装したいと思うでしょうが、これは簡単にするために除外しています。

マークアップ...

<Window x:Class="WpfApplication4.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication4" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.DataContext> 
     <local:ViewModel /> 
    </Window.DataContext> 
    <Window.Resources> 
     <local:StringToDateValueConverter x:Key="converter" /> 
    </Window.Resources> 
    <Grid> 
     <TextBlock Grid.Row="0" Grid.Column="2" HorizontalAlignment="Right" Margin="25,5,0,0" Text="{Binding alertTimeStamp, Converter={StaticResource converter}, StringFormat=dd MMM yyyy hh:mm:ss tt}"></TextBlock> 
    </Grid> 
</Window> 
+0

ありがとうございました。 – nikhil

0

I alertTimeStampが既に文字列であることが問題であると思われるので、StringFormatプロパティで変更することはできません。

私は、第二の特性を有する推薦:

public DateTime AlertTimeStampDateTime 
{ 
    get { return DateTime.Parse(this.alertTimeStamp); } 
} 

次に同じStringFormatプロパティで<TextBlock />オブジェクトにAlertTimeStampDateTimeプロパティをバインドします。

さらに、同じことを行うIValueConverterを実装するクラスを作成できます。 StringToDateTimeコンバーターを使用することもできますし、StringFormatプロパティをさらに使用したり、TimestampConverterを入力してをDateTimeに変更したり、上記のフォーマット文字列でDateTimeをフォーマットしたりして、stringを出力することができます。この繰り返しでは、StringFormatプロパティは必要ありません。

+0

は確かに私はそれを与えてみましょう試してみる。 – nikhil

関連する問題