Click here to Skip to main content
14,691,021 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
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)
                {
                }

            }          
        }
    }
}
Posted
Updated 19-Jan-12 1:00am
v3
Comments
Wonde Tadesse 1-Nov-12 20:29pm
   
Try to separate a business from UI. Your datatable shouldn't be constructed here in UI.

Maybe this will help you
Change cell color[^]
   
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
   
v2
I would recommend creating a behavior (see Introduction to Attached Behaviors in WPF[^]). In this behavior subscribe to the LostFocus event. You will have to have an extra DependencyProperty to save the old value. The sender will be the control, so can do whatever formatting you want. Here is another thread on this topic: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/790d35dc-8000-4d69-a60d-d46a6b7c75ae[^]
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900