如何在XAML元素中使用StringFormat?

Edw*_*uay 53 xaml string-formatting

我深陷在一个绑定订单的XAML堆栈元素中.

订单日期显示为例如"12/31/2008 12:00:00 AM".

我希望它显示为例如"31.12.2008".

我怎样才能做到这一点?我已经看到其他stackoverflow问题提到StringFormat,但他们使用多绑定的方式,我无法工作.

这是我想要的那种语法(这是伪代码),只需在需要的地方指定StringFormat,这有可能吗?

<StackPanel>
    <ListView ItemsSource="{Binding Orders}">
        <ListView.View>
            <GridView>
                <GridViewColumn 
                    Header="Order ID" 
                    DisplayMemberBinding="{Binding Path=OrderID}"
                    StringFormat="{}{1:dd.MM.yyyy}"/>
                <GridViewColumn 
                    Header="Order Date" 
                    DisplayMemberBinding="{Binding Path=OrderDate}"/>
            </GridView>
        </ListView.View>
    </ListView>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

Raz*_*zie 80

我没有测试过,但我认为这应该有效:

<GridViewColumn
    Header="Order Date"
    DisplayMemberBinding=
        "{Binding Path=OrderDate, StringFormat='{}{0:dd.MM.yyyy}'}"/>
Run Code Online (Sandbox Code Playgroud)

  • 并且您可以在字符串的任一侧附加文本,例如"开始日期:{0:dd-MM-yyyy}" (3认同)

Oli*_*ais 28

通常,您可以查找关联的*StringFormat依赖项属性.例如,所有ContentControl实现(例如Label和Tooltip)都具有ContentStringFormat依赖项属性:

<Label
    Content="{Binding Path=DateAsked}"
    ContentStringFormat="{}{0:yyyy/MM/dd HH:mm:ss}" />
Run Code Online (Sandbox Code Playgroud)

在你的情况,而GridViewColumnHeaderStringFormat依赖属性与附和Header,没有模拟的DisplayMemberBinding,所以你需要.NET 3.5 SP1(用得到它的Visual Studio 2008 SP1),或更好地使用新BindingBase.StringFormat财产:

<GridViewColumn 
    Header="Order ID"
    DisplayMemberBinding="{Binding Path=OrderID, StringFormat='{}{0:dd.MM.yyyy}'}"
/>
Run Code Online (Sandbox Code Playgroud)

在博客文章中有更多的例子试试Binding.StringFormat.