Изменение цвета ячейки WPF Datagrid
Уважаемый друг,
В настоящее время я работаю над приложением для торговли акциями. В этом приложении я работаю над наблюдением за рынком. Для этого наблюдения за рынком я использую 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" 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>
а код C# - это
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) { } } } } }
Wonde Tadesse
Попробуйте отделить бизнес от пользовательского интерфейса. Ваш datatable не должен быть построен здесь, в пользовательском интерфейсе.