WPF: How do I apply custom formatting to a ListView?

纵然是瞬间 提交于 2020-06-28 04:07:48

问题


My ListView is petty simple:

<ListView ItemsSource="{Binding Path=ActiveCounters}">
    <ListView.View>
        <GridView>
            <GridViewColumn  Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
            <GridViewColumn  Header="Value"  DisplayMemberBinding="{Binding Path=Value}" />
            <GridViewColumn  Header="As Of Date"  DisplayMemberBinding="{Binding Path=AsOfDate}" />
            <GridViewColumn  Header="Duration"  DisplayMemberBinding="{Binding Path=Duration}" />
            <GridViewColumn  Header="Last Modified Date"  DisplayMemberBinding="{Binding Path=Timestamp}" />
        </GridView>
    </ListView.View>
</ListView>

What I want to do is:

  • Format "Value" using the built-in format "D0"
  • Format "AsOfDate" and "Last Modified Date" using the custom string "MMM d hh:mm:ss tt"
  • Format "Duration" with a function defined as "String DurationString(TimeSpan)

回答1:


For Value and AsOfDate columns use StringFormat attribute - a new feature of WPF 3.5 SP1. More about it here:

http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx

http://elegantcode.com/2009/04/07/wpf-stringformat-in-xaml-with-the-stringformat-attribute/

If you want to call a custom function on a bound value, then implement a value converter for that.

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

You can call your custom function from convert method.




回答2:


StringFormat can be added to your binding statement. For example

<GridViewColumn
   Header="As Of Date"
   DisplayMemberBinding="{Binding Path=AsOfDate, StringFormat={}{0:MMM d hh:mm:ss tt}}" />

See this post for more usage examples



来源:https://stackoverflow.com/questions/2144292/wpf-how-do-i-apply-custom-formatting-to-a-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!