using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
using System.Reflection;
namespace CustCellLab
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
List<SimData> data = new List<SimData>();
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
//以亂數摸擬資料
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
data.Add(new SimData()
{
SN = i.ToString("00000"),
ScoreA = 100 - rnd.Next(199),
ScoreB = 100 - rnd.Next(199)
});
}
//方法1: 使用DataGridTemplateColumn + IValueConverter
dg1.ItemsSource = data;
#region 方法2: 利用LoadingRow事件加工
SolidColorBrush normal = new SolidColorBrush(Colors.Green);
SolidColorBrush negative = new SolidColorBrush(Colors.Red);
dg2.LoadingRow += (s, o) =>
{
//o為DataGridRowEventArgs
SimData sd = o.Row.DataContext as SimData;
//巡過所有欄位,找出Score*
foreach (DataGridColumn c in dg2.Columns)
{
if (c.Header.ToString().StartsWith("Score"))
{
//動態取得TextBlock物件
TextBlock tb =
c.GetCellContent(o.Row) as TextBlock;
//o.Row.DataContext就是SimData, 可以Hard-Coding去取sd.ScoreA/B
//這裡則示範用Reflection法取Binding目標欄位值
PropertyInfo pi = sd.GetType().GetProperty(
(c as DataGridTextColumn).Binding.Path.Path);
decimal v = Convert.ToDecimal(pi.GetValue(sd, null));
tb.Foreground = (v >= 0) ? normal : negative;
}
}
};
dg2.ItemsSource = data;
#endregion
dg3.ItemsSource = data;
}
}
public class SimData
{
public string SN { get; set; }
public decimal ScoreA { get; set; }
public decimal ScoreB { get; set; }
}
#region CellTemplate & ValueConverter
//REF: http://bit.ly/dCFcBY
public class ScoreColorConverter : IValueConverter
{
static SolidColorBrush NormalColor =
new SolidColorBrush(Colors.Green);
static SolidColorBrush NegColor =
new SolidColorBrush(Colors.Red);
//依數字正負採用不同顏色
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
decimal score = System.Convert.ToDecimal(value);
return score >= 0 ? NormalColor : NegColor;
}
public object ConvertBack(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
throw new NotSupportedException();
}
}
#endregion
#region CustDataColumn
public class ScoreColumn : DataGridTextColumn
{
static ScoreColorConverter scc = new ScoreColorConverter();
protected override FrameworkElement GenerateElement(
DataGridCell cell, object dataItem)
{
//GenerateElement可以用來任意組裝要呈現的元素, 很有彈性
TextBlock tb =
base.GenerateElement(cell, dataItem) as TextBlock;
//此例用Binding.Converter的方法動態換色
//若不用Converter,用轉型或Refelection取出dataItem的值做判斷亦可
Binding b =
new System.Windows.Data.Binding(this.Binding.Path.Path);
b.Converter = scc;
tb.SetBinding(TextBlock.ForegroundProperty, b);
//示範在程式端設定Style
tb.TextAlignment = TextAlignment.Center;
return tb;
}
}
#endregion
}