WPF Datagrid单元格颜色更改 [英] WPF Datagrid Cell color change
问题描述
亲爱的朋友们,
目前我正在进行Stock Tradding申请。在那个应用程序中,我正在研究Market watch。对于那个市场观察,我正在使用Wpftoolkit Datagrid。现在我成功地显示了数据。
现在问题是我想根据细胞当前值和之前的值的差异来改变特定细胞的背景颜色。可以任何人建议我技巧
我的XAML代码是
< Window x:Class = WpfApplication2.Window1
xmlns = http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x = http://schemas.microsoft.com/winfx/2006/xaml
xmlns:wpftoolkit = http://schemas.microsoft.com/wpf/2008/toolkit
标题 = Window1 高度 = 300 宽度 = 500 已移除 = 黑色 前景 = 黄金 >
< 边框 >
< DockPanel >
< 按钮 名称 = btnStart DockPanel.Dock = Top 内容 = 开始 单击 = btnStart_Click > < /按钮 >
< wpftoolkit:DataGrid x:名称 = grid 已删除 = 黑色 前景 = 白色 AutoGenerateColumns = False SelectionUnit < span class =code-keyword> = 单元格 IsReadOnly = True GridLinesVisibility = 无 TargetUpdated = grid_TargetUpdated SourceUpdated = grid_SourceUpdated >
< wpftoolkit:DataGrid.Columns >
< wpftoolkit: DataGridTextColumn 标题 = 公司名称 前景 = 白色 x:Name = cmpname 绑定 = {Binding Path = cmpName} / >
< wpftoolkit: DataGridTextColumn 标题 = TOKEN 前景 = 白色 x:名称 = 令牌 绑定 = {Binding Path = Token} / >
< wpftoolkit:DataGridTextColumn 标题 = BYE QTY x:名称 = bqty 绑定 < span class =code-keyword> = {Binding Path = Bqty,NotifyOnSourceUpdated = True} / >
< wpftoolkit:DataGridTextColumn 标题 = 购买价格 x:名称 = bprice 绑定 = {绑定路径= B. Price,NotifyOnSourceUpdated = True} / >
< wpftoolkit:DataGridTextColumn 标题 = 卖出数量 x:名称 = sqty 绑定 = {Binding Path = Sqty,NotifyOnSourceUpdated = True} / >
< wpftoolkit :DataGridTextColumn 温泉n> 标题 = 卖出价格 x:名称 = sprice 前景 = 白色 绑定 = {Binding Path = SPrice,NotifyOnSourceUpdated = True} 宽度 = 1 * / < span class =code-keyword>>
< / wpftoolkit:DataGrid.Columns >
< ; wpftoolkit:DataGrid.CellStyle >
< 样式 TargetType = {x:输入wpftoolkit:DataGridCell} >
< Setter 属性 = 背景 值 = 黑色 > < / Setter >
< / Style >
< / wpftoolkit:DataGrid.CellStyle >
< wpftoolkit:DataGrid.Style >
< 样式 TargetType = {x:输入wpftoolkit:DataGrid } >
< Setter 属性 = GridLinesVisibility 值 = 无 > < / Setter >
< / Style >
< span class =code-keyword>< / wpftoolkit:DataGrid.Style >
< / wpftoolkit:DataGrid >
< / DockPanel >
< span class =code-keyword>< / Border >
< / Window >
和C#代码是
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;使用System.Windows
;使用System.Windows.Controls
;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;使用System.Windows.Navigation
;
使用System.Windows.Shapes;
使用System.Data;
使用System.Net;
使用System.Net.Sockets;
使用System.Data.SqlServerCe;使用System.ComponentModel
;
使用Microsoft.Windows.Controls;
使用System.Windows.Controls.Primitives;使用VISION_MARKET_WATCH
;
使用System.Collections.Specialized;
名称空间WpfApplication2
{
///< summary>
/// Window1.xaml的互动逻辑
///< / summary>
public partial class Window1:Window
{
DataTable dt = new DataTable();
BackgroundWorker bw = new BackgroundWorker();
public Window1()
{
InitializeComponent();
DataGrid myGrid = new DataGrid();
CollectionView myCollectionView =(CollectionView)CollectionViewSource.GetDefaultView(myGrid.Items);
((INotifyCollectionChanged)myCollectionView).CollectionChanged + = new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged);
dt.Columns.Add(cmpName,typeof(String));
dt.Columns.Add(Token,typeof(String));
dt.Columns.Add(Bqty,typeof(String));
dt.Columns.Add(BPrice,typeof(String));
dt.Columns.Add(Sqty,typeof(String));
dt.Columns.Add(SPrice,typeof(String));
FillGrid();
bw.DoWork + =新的DoWorkEventHandler(backgroundWorker1_DoWork);
bw.WorkerReportsProgress = true;
bw.ProgressChanged + = new ProgressChangedEventHandler(BackgroundWorker1_ProgressChanged);
}
private void FillGrid()
{
string s =c:\\SimDB.sdf;
// string s = Path.GetFullPath(System.Windows.Forms.Application.StartupPath +\\+\\SimDB.sdf);
string dbfile =Persist Security Info = False; Data Source =+ s +;;
SqlCeConnection connection = new SqlCeConnection(datasource =+ dbfile);
connection.Open();
SqlCeDataAdapter da = new SqlCeDataAdapter(选择*来自NSEList.token = profile.token上的NSEList内部联接配置文件,其中shortcode ='EQ',连接);
DataSet ds = new DataSet();
da.Fill(ds);
connection.Close();
da = null;
for(int cnt = 0; cnt< ds.Tables [0] .Rows.Count - 1; cnt ++)
{
DataRow drow = dt.NewRow() ;
drow [cmpName] = ds.Tables [0] .Rows [cnt] [ShortName]。ToString();
drow [Token] = ds.Tables [0] .Rows [cnt] [Token]。ToString();
drow [Bqty] =;
drow [BPrice] =;
drow [Sqty] =;
drow [SPrice] =;
dt.Rows.Add(卓尔);
}
grid.ItemsSource = dt.DefaultView;
//grid.Background = Brushes.Black; 1
//grid.BorderStyle = System.Windows.Forms.BorderStyle.None;
}
private void btnStart_Click(object sender,RoutedEventArgs e)
{
bw.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
{
processBroadCast();
}
private void BackgroundWorker1_ProgressChanged(System.Object obj,System.ComponentModel.ProgressChangedEventArgs e)
{
this.Dispatcher.BeginInvoke((Action)delegate() {
dt =(DataTable)e.UserState;
//grid.Items.Refresh();
});
DataTrigger dg = new DataTrigger();
}
private DataTable processBroadCast()
{
UdpClient cli = new UdpClient(7864);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(127.0.0.1),7864);
while(true)
{
byte [] data = cli.Receive(ref ep);
MWProperties mwproc = new MWProperties();
BASEMAIN.CallingMethod(ref mwproc,data);
DataTable dt2 = ChangeGrid(ref mwproc);
data = null;
mwproc = null;
bw.ReportProgress(0,dt2);
}
// peer = null;
}
// public DataGridRow GetRow(int index)
// {
// DataGridRow row =(DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
// if(row == null)
// {
// //可以虚拟化,进入视图并再次尝试
// DataGrid_Standard.ScrollIntoView(DataGrid_Standard。项[指数]);
// row =(DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
//}
//返回行;
//}
// public DataGridCell GetCell(int row,int column)
// {
// DataGridRow rowContainer = GetRow(row);
// if(rowContainer!= null)
// {
// DataGridCellsPresenter presenter = GetVisualChild< DataGridCellsPresenter>(rowContainer);
// //尝试获取单元格,但它可能是虚拟化的
// DataGridCell cell =(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
// if(cell == null)
// {
// //现在尝试进入视图并检索单元
// DataGrid_Standard.ScrollIntoView(rowContainer, DataGrid_Standard.Columns [柱]);
// cell =(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
//}
//返回单元格;
//}
//返回null;
//}
private DataTable ChangeGrid(ref MWProperties mwproc)
{
DataTable dt1 = dt;
short i = mwproc.Token;
//Microsoft.Windows.Controls.DataGridCell cell = new Microsoft.Windows.Controls.DataGridCell();
try
{
if(mwproc == null)
{
}
else
{
for(int k = 0; k< grid.Items.Count - 1; k ++)
{
if(dt1.Rows [k] [Token]!= null)
{
if(dt1.Rows [k] [Token]。ToString()== i.ToString())
{
dt1.Rows [k] [Bqty] = mwproc.MBPINFORMATION [ 0] .Quantity.ToString();
dt1.Rows [k] [BPrice] =(decimal.Round(mwproc.MBPINFORMATION [0] .Price,2)/ 100).ToString();
dt1.Rows [k] [Sqty] = mwproc.MBPINFORMATION [5] .Quantity.ToString();
dt1.Rows [k] [SPrice] =(decimal.Round(mwproc.MBPINFORMATION [5] .Price,2)/ 100).ToString();
}
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message) );
}
返回dt1;
}
private void DataGrid_CollectionChanged(object sender,NotifyCollectionChangedEventArgs e)
{
}
private void grid_TargetUpdated(object sender,DataTransferEventArgs e)
{
}
private void grid_SourceUpdated(object sender,DataTransferEventArgs e)
{
if(e.OriginalSource!= null&& e.TargetObject! = null)
{
DependencyProperty prop = e.Property;
DataGrid src =(DataGrid)e.Source;
try
{
TextBlock obnew =(TextBlock)e.OriginalSource;
TextBlock objold =(TextBlock)e.TargetObject;
if(obnew.Text!= objold.Text)
{
double pre,no;
布尔值b1 = double.TryParse(objold.Text.ToString(),out pre);
布尔值b2 = double.TryParse(obnew.Text.ToString(),out no);
if(b1 == true&& b2 == true)
{
if(pre> no)
{
obnew.Background = Brushes。红色;
}
其他
{
obnew.Background = Brushes.Green;
}
}
}
}
catch(例外情况)
{
}
}
}
}
}
也许这会对你有所帮助
更改单元格颜色 [ ^ ]
您好,
尝试查看以下链接:
http://stackoverflow.com/questions/1847359/wpf-programatically-assingin-a-color-to-row-in-datagrid 一> [ ^ ]
http://social.msdn.microsoft.com/Forums/en/wpf/thread/ 8e598d5e-2e64-476d-941b-546a821aaa88 [ ^ ]
问候
Robert
>
为背景颜色写一个样式触发器
< 样式 x:key = BackgroundColorStyle xmlns:x = #known TargetType = {x:输入wpftoolkit:DataGrid} >
<设定器>
Property =Background
Value ={ Binding COLORS }> ;
< / setter >
< / style >
COLORS是一个数据表列,应该包含任何颜色名称
Dear friends,
Currently I am working on Stock Tradding application. In that application I am working on Market watch. For that market watch I am using Wpftoolkit Datagrid. Now I am successfull in showing the Data.
Now the problem is I want to change the background color of paricular cell based on the difference of that cell's current value and previous value.Can any one suggest me the trick
My XAML Code is
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpftoolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="500" removed="Black" Foreground="Gold">
<Border>
<DockPanel>
<Button Name="btnStart" DockPanel.Dock="Top" Content="Start" Click="btnStart_Click"></Button>
<wpftoolkit:DataGrid x:Name="grid" removed="Black" Foreground="White" AutoGenerateColumns="False" SelectionUnit="Cell" IsReadOnly="True" GridLinesVisibility="None" TargetUpdated="grid_TargetUpdated" SourceUpdated="grid_SourceUpdated">
<wpftoolkit:DataGrid.Columns>
<wpftoolkit:DataGridTextColumn Header="Company Name" Foreground="White" x:Name="cmpname" Binding ="{Binding Path=cmpName}" />
<wpftoolkit:DataGridTextColumn Header="TOKEN" Foreground="White" x:Name="token" Binding ="{Binding Path=Token}"/>
<wpftoolkit:DataGridTextColumn Header="BYE QTY" x:Name="bqty" Binding ="{Binding Path=Bqty,NotifyOnSourceUpdated =True}"/>
<wpftoolkit:DataGridTextColumn Header="BUY PRICE" x:Name="bprice" Binding ="{Binding Path=BPrice, NotifyOnSourceUpdated =True}"/>
<wpftoolkit:DataGridTextColumn Header="SELL QTY" x:Name="sqty" Binding ="{Binding Path=Sqty,NotifyOnSourceUpdated =True}"/>
<wpftoolkit:DataGridTextColumn Header="SELL PRICE" x:Name="sprice" Foreground="White" Binding ="{Binding Path=SPrice,NotifyOnSourceUpdated =True}" Width="1*"/>
</wpftoolkit:DataGrid.Columns>
<wpftoolkit:DataGrid.CellStyle>
<Style TargetType="{x:Type wpftoolkit:DataGridCell}">
<Setter Property="Background" Value="Black"></Setter>
</Style>
</wpftoolkit:DataGrid.CellStyle>
<wpftoolkit:DataGrid.Style>
<Style TargetType="{x:Type wpftoolkit:DataGrid}">
<Setter Property="GridLinesVisibility" Value="None"></Setter>
</Style>
</wpftoolkit:DataGrid.Style>
</wpftoolkit:DataGrid>
</DockPanel>
</Border>
</Window>
and C# Code is
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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; using System.Data; using System.Net; using System.Net.Sockets; using System.Data.SqlServerCe; using System.ComponentModel; using Microsoft.Windows.Controls; using System.Windows.Controls.Primitives; using VISION_MARKET_WATCH; using System.Collections.Specialized; namespace WpfApplication2 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { DataTable dt = new DataTable(); BackgroundWorker bw = new BackgroundWorker(); public Window1() { InitializeComponent(); DataGrid myGrid = new DataGrid(); CollectionView myCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(myGrid.Items); ((INotifyCollectionChanged)myCollectionView).CollectionChanged += new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged); dt.Columns.Add("cmpName", typeof(String)); dt.Columns.Add("Token", typeof(String)); dt.Columns.Add("Bqty", typeof(String)); dt.Columns.Add("BPrice", typeof(String)); dt.Columns.Add("Sqty", typeof(String)); dt.Columns.Add("SPrice", typeof(String)); FillGrid(); bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); bw.WorkerReportsProgress = true ; bw.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker1_ProgressChanged); } private void FillGrid() { string s = "c:\\SimDB.sdf"; //string s = Path.GetFullPath(System.Windows.Forms.Application.StartupPath + "\\" + "\\SimDB.sdf"); string dbfile = "Persist Security Info = False;Data Source=" + s + ";"; SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile); connection.Open(); SqlCeDataAdapter da = new SqlCeDataAdapter("select * from NSEList inner join profile on NSEList.token = profile.token where shortcode = 'EQ'", connection); DataSet ds = new DataSet(); da.Fill(ds); connection.Close(); da = null; for (int cnt = 0; cnt < ds.Tables[0].Rows.Count - 1; cnt++) { DataRow drow = dt.NewRow(); drow["cmpName"] = ds.Tables[0].Rows[cnt]["ShortName"].ToString(); drow["Token"] = ds.Tables[0].Rows[cnt]["Token"].ToString(); drow["Bqty"] = ""; drow["BPrice"] = ""; drow["Sqty"] = ""; drow["SPrice"] = ""; dt.Rows.Add(drow); } grid.ItemsSource = dt.DefaultView; //grid.Background = Brushes.Black;1 //grid.BorderStyle = System.Windows.Forms.BorderStyle.None; } private void btnStart_Click(object sender, RoutedEventArgs e) { bw.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { processBroadCast(); } private void BackgroundWorker1_ProgressChanged(System.Object obj, System.ComponentModel.ProgressChangedEventArgs e) { this.Dispatcher.BeginInvoke((Action)delegate() { dt = (DataTable)e.UserState; //grid.Items.Refresh(); }); DataTrigger dg = new DataTrigger(); } private DataTable processBroadCast() { UdpClient cli = new UdpClient(7864); IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7864); while (true) { byte[] data = cli.Receive(ref ep); MWProperties mwproc = new MWProperties(); BASEMAIN.CallingMethod(ref mwproc, data); DataTable dt2 = ChangeGrid(ref mwproc); data = null; mwproc = null; bw.ReportProgress(0, dt2); } //peer = null; } //public DataGridRow GetRow(int index) //{ // DataGridRow row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index); // if (row == null) // { // // may be virtualized, bring into view and try again // DataGrid_Standard.ScrollIntoView(DataGrid_Standard.Items[index]); // row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index); // } // return row; //} //public DataGridCell GetCell(int row, int column) //{ // DataGridRow rowContainer = GetRow(row); // if (rowContainer != null) // { // DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); // // try to get the cell but it may possibly be virtualized // DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); // if (cell == null) // { // // now try to bring into view and retreive the cell // DataGrid_Standard.ScrollIntoView(rowContainer, DataGrid_Standard.Columns[column]); // cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); // } // return cell; // } // return null; //} private DataTable ChangeGrid(ref MWProperties mwproc) { DataTable dt1 = dt; short i = mwproc.Token; //Microsoft.Windows.Controls.DataGridCell cell = new Microsoft.Windows.Controls.DataGridCell(); try { if (mwproc == null) { } else { for (int k = 0; k < grid.Items.Count - 1; k++) { if (dt1.Rows[k]["Token"] != null) { if (dt1.Rows[k]["Token"].ToString() == i.ToString()) { dt1.Rows[k]["Bqty"] = mwproc.MBPINFORMATION[0].Quantity.ToString(); dt1.Rows[k]["BPrice"] = (decimal.Round(mwproc.MBPINFORMATION[0].Price, 2) / 100).ToString(); dt1.Rows[k]["Sqty"] = mwproc.MBPINFORMATION[5].Quantity.ToString(); dt1.Rows[k]["SPrice"] = (decimal.Round(mwproc.MBPINFORMATION[5].Price, 2) / 100).ToString(); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } return dt1; } private void DataGrid_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { } private void grid_TargetUpdated(object sender, DataTransferEventArgs e) { } private void grid_SourceUpdated(object sender, DataTransferEventArgs e) { if (e.OriginalSource != null && e.TargetObject != null) { DependencyProperty prop = e.Property; DataGrid src = (DataGrid)e.Source; try { TextBlock obnew = (TextBlock)e.OriginalSource; TextBlock objold = (TextBlock)e.TargetObject; if (obnew.Text != objold.Text) { double pre, no; Boolean b1 = double.TryParse(objold.Text.ToString(), out pre); Boolean b2 = double.TryParse(obnew.Text.ToString(), out no); if (b1 == true && b2 == true) { if (pre > no) { obnew.Background = Brushes.Red; } else { obnew.Background = Brushes.Green; } } } } catch (Exception ex) { } } } } }
Maybe this will help you
Change cell color[^]
Hi,
try to check following links:
http://stackoverflow.com/questions/1847359/wpf-programatically-assingin-a-color-to-row-in-datagrid[^]
http://social.msdn.microsoft.com/Forums/en/wpf/thread/8e598d5e-2e64-476d-941b-546a821aaa88[^]
Regards
Robert
write a style trigger for background color
<style x:key="BackgroundColorStyle" xmlns:x="#unknown" TargetType="{x:Type wpftoolkit:DataGrid}"> <setter> Property="Background" Value="{Binding COLORS}"> </setter> </style>
COLORS is a datatable column that should contain any color name
这篇关于WPF Datagrid单元格颜色更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!