WPF 3.5 SP1の新機能 - StringFormat

Lester's WPF blog : WPF 3.5 SP1 feature: StringFormat



これまでWPFではバインディングした値に対して書式を設定するという機能は用意されていませんでした。そのため、たとえば100という値を100円と表示したいといった場合には、そのためだけにConverterを作成するか、あるいはテンプレートをそのように書き換えるといった方法で対応する必要がありました。


WPF 3.5 SP1には、BindingBaseにStringFormatプロパティが用意されており、これを使って簡単な書式が設定できるようになっています。


Visual Basic

Class Window1
 
    Public Class Data
 
        Private _date As DateTime
        Private _int As Integer
 
        Public Property TestDate() As DateTime
            Get
                TestDate = _date
            End Get
            Set(ByVal value As DateTime)
                _date = value
            End Set
        End Property
 
        Public Property TestInt() As Integer
            Get
                TestInt = _int
            End Get
            Set(ByVal value As Integer)
                _int = value
            End Set
        End Property
 
        Public Sub New(ByVal _date As DateTime, ByVal _int As Integer)
            TestDate = _date
            TestInt = _int
        End Sub
 
    End Class
 
    Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Dim testData As New Data(DateTime.Today, 3333)
        Window1.DataContext = testData
 
        Dim testCollectionData As New ObjectModel.ObservableCollection(Of Data)
        testCollectionData.Add(New Data(DateTime.Today, 3333))
        ListView1.ItemsSource = testCollectionData
 
    End Sub
 
End Class


XAML
<Window x:Class="Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:sys="clr-namespace:System;assembly=mscorlib"
   Title="Window1" Height="300" Width="300" Name="Window1">
    <StackPanel>
        <TextBox Text="{Binding Path=TestDate, StringFormat=D}"/>
        <TextBox Text="{Binding Path=TestDate, StringFormat=D}" Language="ja-JP"/>
        <TextBox Text="{Binding Path=TestDate, StringFormat=yyyy年MM月dd日}"/>
        <TextBox Text="{Binding Path=TestDate, StringFormat=ggyy年MM月dd日}"/>
        <TextBox Text="{Binding Path=TestDate, StringFormat=ggyy年MM月dd日}" Language="ja-JP"/>
 
        <TextBox Text="{Binding Path=TestInt, StringFormat=金額: {0:C}}"/>
        <TextBox Text="{Binding Path=TestInt, StringFormat=金額: {0:C}}" Language="ja-JP"/>
 
        <ListBox ItemStringFormat="P">
            <sys:Double>0.23</sys:Double>
            <sys:Double>0.46</sys:Double>
        </ListBox>
 
        <Expander Content="{Binding TestInt}" ContentStringFormat="X"/>
 
        <ListView Name="ListView1">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="日付" DisplayMemberBinding="{Binding Path=TestDate, StringFormat=D}"/>
                    <GridViewColumn Header="金額" DisplayMemberBinding="{Binding Path=TestInt, StringFormat={}{0}円}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </StackPanel>
</Window>