1. 程式人生 > 實用技巧 >格式化繫結的資料

格式化繫結的資料

資料轉換stringFormat

<Window x:Class="WpfApplicationDEMO.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" 
       >
    <Window.Resources>
        <Style TargetType="
TextBlock"> <Setter Property="Height" Value="30"></Setter> </Style> </Window.Resources> <StackPanel> <TextBlock Text="{Binding Path=Price, StringFormat={}{0:C}}" ></TextBlock> <TextBlock Text="{Binding Path=Price, StringFormat=The Value is {0:C}}
" ></TextBlock> <TextBlock Text="{Binding Path=Price, StringFormat=The Value is {0:E}}"></TextBlock> <TextBlock Text="{Binding Path=Price, StringFormat=The Value is {0:P}}"></TextBlock> <TextBlock Text="{Binding Path=Price, StringFormat=The Value is {0:F2}}
"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:d}}"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:D}}"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:f}}"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:F}}"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:s}}"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:M}}"></TextBlock> <TextBlock Text="{Binding Path=CreateDate, StringFormat=The Value is {0:G}}"></TextBlock> </StackPanel> </Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplicationDEMO
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new Product() { Name = "張三", Price = 1.8645f, CreateDate = DateTime.Now };
        }
     
    }

    public class Product
    {
        public string Name { get; set; }
        public float Price { get; set; }
        public DateTime CreateDate { get; set; }
    }
}