首頁

2013年6月28日 星期五

)(KR)세 가지 방법의 색에 의해 결정 실버 DateGrid 의 셀 값))**)(EN)Silverlight DateGaid cell values determined--by the color of the three methods***(CHT)_Silverloght DateGrid)依儲存格值決定顏色的三種方法)(三種語言描寫序式)(언어의 세 가지 종류의 시퀀스 유형을 설명하기 위해)(Three kinds of language to describe sequence type)~~~!!!!!

))(KR)세 가지 방법의 색에 의해 결정 실버 DateGrid 셀 값))**)(EN)Silverlight DateGaid cell values determined--by the color of the three methods***
(CHT)_Silverloght DateGrid)依儲存格值
決定顏色的三種方法)(언어의 세 가지 종류의 시퀀스 유형을 설명하기 위해))(Three kinds of language to describe sequence type))~~~!!!!!

*KR**다른 텍스트 색상 또는 배경색으로 셀 값을 판단 할 수있는 -
 실버 DataGrid를 사용하는 경우, 그것은 종종 수요를 발생합니다.
WPF와 Silverlight 바인딩 및 동작 템플릿 원칙 처음 익숙하지
않은, 참으로, 계몽에 오신 것을 환영합니다, 탐험 나는 반면에
세 가지 접근 메모 마무리 해요 곳을 찾기 위해 어떤 노력을했다.

DG1, DG2, DG3 다음 실버 라이트 프로그램에서 세 가지 데이터

격자를 넣어. 빨간색 마이너스 표시하면 여러 지점의 소스 데이터를 
 각 레코드 쇼에 ScoreB 점수와 ScoreA을 가지고, 우리는 점수
 0을 달성하기 위해 희망, 텍스트, 녹색입니다. DG1, 2,3 색상
부정적인 점수에 따라 효과를 달성하기 위해 각 사용 다른 방법 :

DG1 : 사용 DataGridTemplate, TextBlock에, ScoreA / B 바인딩있는

foregroud 숙박 시설은 넣어하지만 IValueConverter를 추가 빨간색이나
녹색의 번호를 설정합니다

DG2 : 셀의 시각적 요소를 제거하는 DataGridTextColumn.GetCellContent (DataGridRowEventArgs.Row) 방법을 사용하여 DataGrid.LoadingRow

 이벤트, DataGridTextColumn을 사용합니다 
(오른쪽 DataGridTextColumn을 우려 TextBlock의 경우),
TextBlock에, DataGridRowEventArgs.Row 변환. 반사 기술은
 자신의 긍정적이고 부정적인 속성에 따라 TextBlock의
전경 ScoreA 또는 ScoreB 제거하고 조정과 함께 
DataContext에 정보 객체를받을 수 있습니다. 반사 교체 하드 
 코딩이나 경우 장소를 전환 할 수 있습니다 
(예를 들어 : 만약 (c.Header.ToString () == 
 "ScoreA") V = sd.ScoreA;), 또는 당신은 바인딩을 사용 할 
 수 있습니다 + 변환 방식 데이터 속성 전경 값은 
 (이 방법 DG3 보여줍니다) 함께 묶어.

DG3 : 사용자 정의 ScoreColumn, 그것은 긍정적이고 부정적인

전환의 데이터 값으로 수행 할 수 있도록  
DataGridTextColumn을 상속하지만, GenerateElement  
 ()를 재정의 Foreground 속성 플러스 바인딩하기 전에
TextBlock에 반환합니다. 또한, GenerateElement ()는 재미있는  
게임을 많이 변경할 수 동적 인 시각적 요소의 조합을 표시  
반환 할 수 있습니다   ****KR**아래 ***

**When using Silverlight DataGrid, it is often encountered a demand -
to be able to determine the cell value by a different text color or 
 background color. Initially unfamiliar with WPF and Silverlight 
Binding and Template principle of operation is, indeed, took some 
effort to explore, to find out where I'm finishing three different 
approaches, one notes, on the other hand are welcome to enlighten.

In the following Silverlight program, put three DataGrid: dg1, dg2, 

 dg3. Source data for the multiple points, each record have ScoreA 
with ScoreB two scores in the show, we hope to achieve scores of
 0:00 text is green, if negative displayed in red. dg1, 2,3 each use a 
different method to achieve the effect according 
 to color negative score:

dg1: Use DataGridTemplate, put TextBlock, Foregroud property 

Binding to ScoreA / B, but add a IValueConverter will turn 
red or green numbers

dg2: Use DataGridTextColumn, in DataGrid.LoadingRow event, using DataGridTextColumn.GetCellContent (DataGridRowEventArgs.Row) way

to remove the visual elements of the cell (right DataGridTextColumn 
concerned, is TextBlock), its transformation into a TextBlock,
DataGridRowEventArgs.Row. DataContext may obtain information 
object with Reflection techniques remove ScoreA or ScoreB, and 
then adjust the TextBlock Foreground according to their positive 
and negative attributes. Reflection can switch places with  
Hardcoding replaced or if (for example: if (c.Header.ToString () == 
 "ScoreA") v = sd.ScoreA ;), or you can use Binding + Converter  
way the foreground with the data attribute value tied together 
(this practice dg3 demonstrates).

dg3: Customizing a ScoreColumn, inherited from  

DataGridTextColumn, but override GenerateElement (), returns a
TextBlock before the Foreground property plus the Binding, so that 
it can do with the data values ​​of the positive and negative switching.  
 In addition, GenerateElement () can return to display dynamic visual  
 element combinations that can change a lot of interesting gameplay  
 ***EN*Look down*

**
在使用Silverlight DataGrid時,很常遇到一項需求--要能依儲存
格值決定不同的文字顏色或背景色。起初不熟WPF及Silverlight
Binding及Template運作原理,著實花了一些功夫摸索,這裡整理
找出的三種不同做法,一方面備忘,另一方面歡迎大家指教。
在以下的Silverlight程式中,放了三個DataGrid: dg1, dg2, dg3。
資料來源為多筆分數資料,每筆記錄各有ScoreA與ScoreB兩個 
分數,在顯示時,希望做到分數>0時文字為綠色,若為負數則以 
紅色顯示。dg1,2,3各使用不同的方法達成依分數正負變色的效果:
dg1: 使用DataGridTemplate,放入TextBlock,Foregroud屬性 
Binding至ScoreA/B,但加掛IValueConverter將數字轉為紅色或綠色

dg2: 使用DataGridTextColumn,在DataGrid.LoadingRow事件中,
利用DataGridTextColumn.GetCellContent  
(DataGridRowEventArgs.Row)的方式取出儲存格中的視覺元素 
(對DataGridTextColumn而言,就是TextBlock),
將其轉型為TextBlock,DataGridRowEventArgs.Row.
DataContext可取得資料物件,用Reflection的技巧取出ScoreA
或ScoreB,再依其正負調整TextBlock的Foreground屬性。
Reflection的地方可以用switch或if配合Hardcoding取代(例如:  
if (c.Header.ToString() == "ScoreA") v = sd.ScoreA;),
或者可以用Binding + Converter方式將前景色跟資料
屬性值綁在一起(此做法dg3會示範)。

dg3: 自訂一個ScoreColumn,繼承自DataGridTextColumn,
但覆寫GenerateElement(),傳回TextBlock前,為Foreground
屬性加上Binding,使其能隨資料值的正負做切換。另外,
GenerateElement()可以動態傳回要顯示的視覺元素組合,
可以變化出許多有趣的玩法                       **

**
<UserControl x:Class="CustCellLab.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" xmlns:local="clr-namespace:CustCellLab"
d:DesignHeight="300" d:DesignWidth="400" 
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
    Loaded="UserControl_Loaded">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions> 
        <Grid.Resources> 
            <local:ScoreColorConverter x:Key="ScoreColorConverter" /> 
            <Style x:Key="CenterText" TargetType="TextBlock"> 
                <Setter Property="TextAlignment" Value="Center" /> 
            </Style> 
        </Grid.Resources> 
        <sdk:DataGrid Margin="2" Name="dg1" Grid.Row="0" 
AutoGenerateColumns="False"> 
            <sdk:DataGrid.Columns> 
                <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}"/> 
                <sdk:DataGridTemplateColumn Header="ScoreA"> 
                    <sdk:DataGridTemplateColumn.CellTemplate> 
                        <DataTemplate>  
                            <TextBlock Text="{Binding ScoreA}" 
Foreground="{Binding ScoreA, Converter={StaticResource 
ScoreColorConverter}}" 
                                       TextAlignment="Center" />
                        </DataTemplate> 
                    </sdk:DataGridTemplateColumn.CellTemplate> 
                </sdk:DataGridTemplateColumn> 
                <sdk:DataGridTemplateColumn Header="ScoreB"> 
                    <sdk:DataGridTemplateColumn.CellTemplate> 
                        <DataTemplate>
                            <TextBlock Text="{Binding ScoreB}" 
Foreground="{Binding ScoreB, Converter={StaticResource 
ScoreColorConverter}}" 
                                       TextAlignment="Center" /> 
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate> 
                </sdk:DataGridTemplateColumn> 
            </sdk:DataGrid.Columns> 
        </sdk:DataGrid> 
        <sdk:DataGrid Margin="2" Name="dg2" Grid.Row="1" 
AutoGenerateColumns="False"> 
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}" />
                <sdk:DataGridTextColumn Header="ScoreA" 
Binding="{Binding ScoreA}" 
                                        ElementStyle="
{StaticResource CenterText}"/> 
                <sdk:DataGridTextColumn Header="ScoreB" 
Binding="{Binding ScoreB}" 
                                        ElementStyle="
{StaticResource CenterText}" /> 
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <sdk:DataGrid Margin="2" Name="dg3" Grid.Row="2" 
AutoGenerateColumns="False"> 
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}" /> 
                <local:ScoreColumn Header="ScoreA" 
Binding="{Binding ScoreA}" /> 
                <local:ScoreColumn Header="ScoreB" 
Binding="{Binding ScoreB}" /> 
            </sdk:DataGrid.Columns> 
        </sdk:DataGrid> 
    </Grid> 
</UserControl>                                                                     **
 
**
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
}                                                                             **
 
****(KR)*
*<UserControl을 X : 클래스 = "CustCellLab.MainPage"xmlns에 = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns에 : X = 
 "http://schemas.microsoft.com/winfx/2006 / XAML "xmlns에 : 
D ="http://schemas.microsoft.com/expression/blend/2008 "xmlns에 : 
MC ="http://schemas.openxmlformats.org/markup-compatibility/2006 
"MC : 무시 가능한 =" D "xmlns에 : 지역 ="CLR-네임 스페이스 : CustCellLab 
"D : DesignHeight ="300 "D : DesignWidth ="400 "xmlns에 : 
SDK ="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ 
SDK "로드 =" "UserControl_Loaded> <Grid x:Name="LayoutRoot" 
 Background="White"> <Grid.RowDefinitions> <RowDefinition Height="*" 
/> <RowDefinition Height="*" /> <RowDefinition의 높이 = "*"/> </ 
Grid.RowDefinitions> <Grid.Resources> <local:ScoreColorConverter 
x:Key="ScoreColorConverter" /> 스타일 명 x:Key="CenterText" 
TargetType="TextBlock"> <세터 속성 = "TextAlignment 
"값 ="센터 "/> </ 스타일> </ Grid.Resources> <sdk:DataGrid 
Margin="2" Name="d​​g1" Grid.Row="0" AutoGenerateColumns="False"> 
<SDK : DataGrid에. 열> <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}"/> <sdk:DataGridTemplateColumn 
Header="ScoreA"> <sdk:DataGridTemplateColumn.CellTemplate> 
<DataTemplate> <TextBlock의 텍스트 = "{바인딩 ScoreA} "전경 
="{바인딩 ScoreA, 변환기 = {StaticResource의 ScoreColorConverter}} 
"TextAlignment ="센터 "/> </ DataTemplate을> </ SDK : 
DataGridTemplateColumn.CellTemplate> </ SDK : DataGridTemplateColumn> 
<SDK : DataGridTemplateColumn 헤더 ="ScoreB " > 
<sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> 
<TextBlock Text="{Binding ScoreB}" Foreground="{Binding ScoreB,
 Converter={StaticResource ScoreColorConverter}}" 
TextAlignment="Center" </ DataTemplate을> </ SDK :
 DataGridTemplateColumn.CellTemplate> </ SDK : DataGridTemplateColumn> 
 
</ SDK : DataGrid.Columns> </ SDK : DataGrid에> <SDK : DataGrid에 여백 =
 "2"이름 = "DG2"Grid.Row = "1"AutoGenerateColumns를 = "거짓 "> 
<sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}" /> <SDK : DataGridTextColumn을 헤더 ="ScoreA 
"바인딩 ="{바인딩 ScoreA} "ElementStyle ="{StaticResource CenterText}
 "/> <sdk:DataGridTextColumn Header="ScoreB" Binding="{Binding ScoreB}"
 ElementStyle="{StaticResource CenterText}" </ SDK : DataGrid.Columns> 
</ SDK : DataGrid에> <SDK : DataGrid에 여백 = "2"이름 = "DG3"Grid.Row =
 "2"AutoGenerateColumns를 = "거짓"> <sdk:DataGrid.Columns> 
<sdk:DataGridTextColumn Header="SN" Binding="{Binding SN}" /> 
< 지역 : ScoreColumn 헤더 = "ScoreA"바인딩 = "{바인딩 ScoreA}"/> 
<local:ScoreColumn Header="ScoreB" Binding="{Binding ScoreB}" 
</ SDK : DataGrid.Columns> </ SDK : DataGrid에 > </ 그리드> 
</ UserControl을> <UserControl을 X : 클래스 = "CustCellLab.MainPage"
xmlns에이 = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns에 : X = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns에 : D = "http://schemas.microsoft.com/expression/blend/2008"
xmlns에 : MC = "http://schemas.openxmlformats.org/markup-
compatibility/2006"
MC : 무시 가능한 = "D"xmlns에 : 지역 = "CLR-네임 스페이스 : CustCellLab"
D : DesignHeight = "300"D : DesignWidth = "400"
xmlns에 : SDK = "http://schemas.microsoft.com/winfx/2006/
xaml/presentation/sdk"
    로드는 = "UserControl_Loaded">
    <Grid X:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </ Grid.RowDefinitions>
        <Grid.Resources>
            <local:ScoreColorConverter x:Key="ScoreColorConverter" />
            스타일 명 X:Key="CenterText" TargetType="TextBlock">
                <Setter Property="TextAlignment" Value="Center" />
            </ 스타일>
        </ Grid.Resources>
        <sdk:DataGrid Margin="2" Name="d​​g1" Grid.Row="0"
 AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}"/>
                <sdk:DataGridTemplateColumn Header="ScoreA">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <Da​​taTemplate>
                            <TextBlock의 텍스트 = "{바인딩 ScoreA}"
전경 = "{바인딩 ScoreA, 변환기 = {StaticResource의 ScoreColorConverter}}"
                                       TextAlignment = "센터"/>
                        </ DataTemplate을>
                    </ SDK를 : DataGridTemplateColumn.CellTemplate>
                </ SDK를 : DataGridTemplateColumn>
                <sdk:DataGridTemplateColumn Header="ScoreB">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <Da​​taTemplate>
                            <TextBlock의 텍스트 = "{바인딩 ScoreB}"
전경 = "{바인딩 ScoreB, 변환기 = {StaticResource의 ScoreColorConverter}}"
                                       TextAlignment = "센터"/>
                        </ DataTemplate을>
                    </ SDK를 : DataGridTemplateColumn.CellTemplate>
                </ SDK를 : DataGridTemplateColumn>
            </ SDK를 : DataGrid.Columns>
        </ SDK를 : DataGrid에>
        <sdk:DataGrid Margin="2" Name="d​​g2" Grid.Row="1" 
AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}" />
                <SDK를 : DataGridTextColumn을 헤더 =
 "ScoreA"바인딩 = "{바인딩 ScoreA}"
                                        ElementStyle =
 "{StaticResource CenterText}"/>
                <SDK를 : DataGridTextColumn을 헤더 =
 "ScoreB"바인딩 = "{바인딩 ScoreB}"
                                        ElementStyle =
 "{StaticResource CenterText}"/>
            </ SDK를 : DataGrid.Columns>
        </ SDK를 : DataGrid에>
        <sdk:DataGrid Margin="2" Name="d​​g3" Grid.Row="2" 
AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" 
Binding="{Binding SN}" />
                <local:ScoreColumn Header="ScoreA" 
Binding="{Binding ScoreA}" />
                <local:ScoreColumn Header="ScoreB" 
Binding="{Binding ScoreB}" />
            </ SDK를 : DataGrid.Columns>
        </ SDK를 : DataGrid에>
    </ 그리드>
</ UserControl을> 다음과 같이 백엔드 코드 :               *
**시스템을 사용하여, System.Collections.Generic 사용하여,
 System.Linq에 사용; System.Net을 사용하여,
System.Windows를 사용하여, System.Windows.
Controls를 사용하여, System.Windows.Documents를 사용하여,
System.Windows.Input를 사용하여, System.Windows를
사용하여 . 미디어, System.Windows.Media.Animation를 사용하여,
System.Windows.Shapes를 사용하여, System.Windows.
Data를 사용하여, System.Globalization 네임을 사용하여;하는
System.Reflection을 사용하여, 네임 스페이스 CustCellLab
{공용 부분 클래스 MainPage : UserControl을 {공공 MainPage ()
{InitializeComponent를 ();} 목록 <SimData> 데이터 =
 새로운 목록 <SimData> () 개인 무효
UserControl_Loaded (개체를 보낸 사람, RoutedEventArgs E)
{/ / 以 乱 数 摸拟 资料 임의 RND = 새로운 무작위 ()에 대한
(INT I = 0; 나는 <100; 난 + +) {data.Add (새 SimData () {SN = i.ToString
( "00000"), ScoreA = 100 - rnd.Next (199) ScoreB =
 100 - rnd.Next ( 199)});} / /
方法 1 使用 DataGridTemplateColumn +
IValueConverter dg1.ItemsSource = 데이터; # 지역
方法 2 利用 LoadingRow는 事件 加工 SolidColorBrush에
정상 = 새 SolidColorBrush에 (Colors.Green) SolidColorBrush에
부정적인 = 새 SolidColorBrush를은 (Colors.Red )
dg2.LoadingRow + SimData으로 = (S, O) => {/ / O 为
DataGridRowEventArgs SimData SD는 = o.Row.DataContext / /
巡 过 所有 栏 位, 找出 점수 * foreach는 (DataGridColumn의
C DG2합니다. 열) {경우
(c.Header.ToString () StartsWith ( "점수")) {/ / 动态 取得 TextBlock의
物件 TextBlock에 TB TextBlock과 같은 = c.GetCellContent (o.Row). / / o.Row.DataContext 就是 SimData , 可以 하드 코딩 去取 sd.ScoreA /
B / / 这里 则 示范 用 반사 法 取 바인딩 目标 栏 位 值하는
PropertyInfo PI = sd.GetType () GetProperty를 ((C 등
DataGridTextColumn을) Binding.Path.Path.). 소수점 V =
Convert.ToDecimal (pi.GetValue (SD, NULL)); tb.Foreground =
 (V> = 0)? 일반 : 음;}}} dg2.ItemsSource = 데이터; # endregion
dg3.ItemsSource가 = 데이터;}} 공용 클래스 SimData
{공공 문자열 SN은 {얻을; 설정;} 공공 진수 ScoreA {얻을; 설정;}
공공 진수 ScoreB { 얻는다; 설정;}} # 지역 CellTemplate 및
 ValueConverter / / REF : http"//bit.IY/dCFc BY공용 클래스
ScoreColorConverter : IValueConverter {정적 SolidColorBrush에
 NormalColor = 새 SolidColorBrush에 (Colors.Green) 정적
SolidColorBrush에 NegColor = 새 SolidColorBrush에
(색깔 . 레드) / / 依 数字 正负 采用 不同 颜色 공공 개체
(개체 값, 유형 TargetType을, 개체 매개 변수, CultureInfo를 문화)
 변환 {소수 점수 = System.Convert.ToDecimal (값을) 반환 점수>
= 0? NormalColor : NegColor;} 공공 객체 ConvertBack 
 (개체 값, 유형 TargetType을, 개체 매개 변수,
CultureInfo를 문화) {새로운 NotSupportedException이 ()
던져;}} # endregion # 지역 ScoreColumn CustDataColumn
공용 클래스 : DataGridTextColumn을
{정적 ScoreColorConverter SCC = 새로운 ScoreColorConverter
(); 보호 오버라이드 된
FrameworkElement GenerateElement
(DataGridCell 셀 객체 dataItem) {/ / GenerateElement 可以
用来 任意 组装 要 呈现 的 元素, 很有 弹性 TextBlock의
TB TextBlock과 같은 = base.GenerateElement
(셀, dataItem) / / 此 例 用 Binding.Converter的 方法
动态 换 色 / / 若 不用 변환기 用 转型 或 Refelection 取出
dataItem 的 值 做 判断 亦可 바인딩 B = 새로운
System.Windows.Data.Binding (this.Binding.Path.Path)
 b.Converter = SCC; tb.SetBinding
(TextBlock.ForegroundProperty, B) / /
示范 在 程式 端 设定 스타일 tb.TextAlignment =
TextAlignment.Center, 반환 TB;}이} # endregion
}                                                                                                                     ****

**EN**
**<UserControl x: Class = "CustCellLab.MainPage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns: x =
"mc: Ignorable =" d "xmlns: local =" clr-namespace: CustCellLab
 "d: DesignHeight =" 300 "d: DesignWidth =" 400 "xmlns: sdk =" http://schemas.microsoft.com/winfx/2006/xaml/presentation/
 sdk "Loaded =" UserControl_Loaded "> <Grid x:Name=
"LayoutRoot" Background="White"> <Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" /> <RowDefinition Height = "*"
/> </ Grid.RowDefinitions> <Grid.Resources>
<local:ScoreColorConverter x:Key=
"ScoreColorConverter" /> <Style x:Key=
"CenterText" TargetType="TextBlock"> <Setter Property =
"TextAlignment "Value =" Center "/> </ Style> </ Grid.Resources>
<sdk:DataGrid Margin="2" Name="dg1" Grid.Row="0" AutoGenerateColumns="False"> <sdk: DataGrid. Columns>
 <sdk:DataGridTextColumn Header="SN" Binding="{Binding SN}"/> <sdk:DataGridTemplateColumn Header="ScoreA"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate>
<TextBlock Text = "{Binding ScoreA} "Foreground =" {Binding
ScoreA, Converter = {StaticResource ScoreColorConverter}}
"TextAlignment =" Center "/> </ DataTemplate> </ sdk: DataGridTemplateColumn.CellTemplate> </ sdk:
DataGridTemplateColumn> <sdk: DataGridTemplateColumn
Header =" ScoreB " > <sdk:DataGridTemplateColumn.CellTemplate>
 <DataTemplate> <TextBlock Text="{Binding ScoreB}" 
 Foreground="{Binding ScoreB, Converter=
{StaticResource ScoreColorConverter}}" TextAlignment=
"Center" /> </ DataTemplate> </ sdk : DataGridTemplateColumn.
CellTemplate> </ sdk: DataGridTemplateColumn>
</ sdk: DataGrid.Columns> </ sdk: DataGrid>
<sdk: DataGrid Margin = "2" Name = "dg2" Grid.Row =
 "1" AutoGenerateColumns = "False "> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="SN" Binding=
"{Binding SN}" /> <sdk: DataGridTextColumn Header =
" ScoreA "Binding =" {Binding ScoreA} "ElementStyle =
" {StaticResource CenterText} "/> <sdk:DataGridTextColumn 
 Header="ScoreB" Binding="{Binding ScoreB}"
ElementStyle="{StaticResource CenterText}" />
</ sdk: DataGrid.Columns> </ sdk: DataGrid>
<sdk: DataGrid Margin = "2" Name = "dg3" Grid.Row =
 "2" AutoGenerateColumns = "False"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="SN" Binding=
"{Binding SN}" /> < local: ScoreColumn Header =
 "ScoreA" Binding = "{Binding ScoreA}" />
<local:ScoreColumn Header="ScoreB" Binding=
"{Binding ScoreB}" /> </ sdk: DataGrid.Columns>
 </ sdk: DataGrid > </ Grid> </ UserControl> <UserControl x: Class = "CustCellLab.MainPage"
xmlns = "
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns: x = "
http://schemas.microsoft.com/winfx/2006/xaml"
xmlns: d = "
http://schemas.microsoft.com/expression/blend/2008"
xmlns: mc = "
http://schemas.openxmlformats.org/markup-
compatibility/2006"
mc: Ignorable = "d" xmlns: local = "clr-namespace: CustCellLab"
d: DesignHeight = "300" d: DesignWidth = "400"
xmlns: sdk = "
http://schemas.microsoft.com/winfx/2006/
xaml/presentation/sdk"
    Loaded = "UserControl_Loaded">
    <Grid X:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </ Grid.RowDefinitions>
        <Grid.Resources>
            <local:ScoreColorConverter x:Key="ScoreColorConverter" />
            <Style X:Key="CenterText" TargetType="TextBlock">
                <Setter Property="TextAlignment" Value="Center" />
            </ Style>
        </ Grid.Resources>
        <sdk:DataGrid Margin="2" Name="dg1" Grid.Row="0" AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" Binding=
"{Binding SN}"/>
                <sdk:DataGridTemplateColumn Header="ScoreA">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text = "{Binding ScoreA}"
Foreground = "{Binding ScoreA, Converter = {StaticResource
ScoreColorConverter}}"
                                       TextAlignment = "Center" />
                        </ DataTemplate>
                    </ Sdk: DataGridTemplateColumn.CellTemplate>
                </ Sdk: DataGridTemplateColumn>
                <sdk:DataGridTemplateColumn Header="ScoreB">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text = "{Binding ScoreB}"
Foreground = "{Binding ScoreB, Converter = {StaticResource
ScoreColorConverter}}"
                                       TextAlignment = "Center" />
                        </ DataTemplate>
                    </ Sdk: DataGridTemplateColumn.CellTemplate>
                </ Sdk: DataGridTemplateColumn>
            </ Sdk: DataGrid.Columns>
        </ Sdk: DataGrid>
        <sdk:DataGrid Margin="2" Name="dg2" Grid.Row="1" AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="SN" Binding=
"{Binding SN}" />
                <Sdk: DataGridTextColumn Header =
 "ScoreA" Binding = "{Binding ScoreA}"
                                        ElementStyle =
 "{StaticResource CenterText}" />
                <Sdk: DataGridTextColumn Header =
 "ScoreB" Binding = "{Binding ScoreB}"
                                        ElementStyle =
"{StaticResource CenterText}" />
            </ Sdk: DataGrid.Columns>
        </ Sdk: DataGrid>
        <sdk:DataGrid Margin="2" Name="dg3" Grid.Row="2" AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header=
"SN" Binding="{Binding SN}" />
                <local:ScoreColumn Header="ScoreA"
Binding="{Binding ScoreA}" />
                <local:ScoreColumn Header="ScoreB"
Binding="{Binding ScoreB}" />
            </ Sdk: DataGrid.Columns>
        </ Sdk: DataGrid>
    </ Grid>
</ UserControl> backend code as follows:
Display plain text copy text layout
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)
{/ / simulation with random data 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)});} / / Method 1: Use
DataGridTemplateColumn + IValueConverter dg1.ItemsSource =
 data; # region Method 2: Using LoadingRow event processing
SolidColorBrush normal = new SolidColorBrush (Colors.Green);
SolidColorBrush negative = new SolidColorBrush (Colors.Red );
dg2.LoadingRow + = (s, o) => {/ / o is DataGridRowEventArgs
SimData sd = o.Row.DataContext as SimData; / / patrols all fields
 to identify Score * foreach (DataGridColumn c in dg2. Columns)
{if (c.Header.ToString (). StartsWith ("Score")) {/ / dynamically
obtain TextBlock object TextBlock tb = c.GetCellContent (o.Row)
 as TextBlock; / / o.Row.DataContext is SimData You can pick
up Hard-Coding sd.ScoreA / B / / here is taken Binding Model
with Reflection Method target field value 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.Iy/dCFc   BY
public class ScoreColorConverter: IValueConverter
{static SolidColorBrush NormalColor = new SolidColorBrush
 (Colors.Green); static SolidColorBrush NegColor =
new SolidColorBrush (Colors.Red); / / by using positive
and negative numbers in different colors public object
Convert (object value, Type targetType, object parameter,
 CultureInfo culture) {decimal score = System.Convert.To
Decimal (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 can be used to render
 any assembly elements very flexible TextBlock tb = base.
GenerateElement (cell, dataItem) as TextBlock; / / This example
 uses dynamic color changing Binding.Converter method / /
if no Converter, with a transition or Refelection remove
dataItem values ​​to make a judgment may Binding b = new System.Windows.Data.Binding (this.Binding.Path.Path);
b.Converter = scc; tb.SetBinding (TextBlock.ForegroundProperty,
b); / / client settings in the program demonstration Style tb.
TextAlignment = TextAlignment. Center; return tb;}} # endregion
 }                                                                                                                                    **

****
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&