Monday, 23 August 2010

WPF blinking cell

<Window x:Class="WpfTable.Window6"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
    Title="Window6" Height="158" Width="271">
    <Window.Resources>
        <DataTemplate x:Key="BlinkCellTemplate">                        
            <TextBlock TextAlignment="Center" x:Name="tbMessage" Background="White" Padding="5,0,0,0">
            <TextBlock.Text>
                <Binding Path="Price" NotifyOnTargetUpdated="True">
                    <Binding.StringFormat>{0:#.0000}</Binding.StringFormat>
                </Binding>                
            </TextBlock.Text>
            <TextBlock.Triggers>
                <EventTrigger RoutedEvent="Binding.TargetUpdated">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)" From="White" To="Red" Duration="0:0:1"></ColorAnimation>
                            <ColorAnimation Storyboard.TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)" From="Red" To="White" Duration="0:0:1"></ColorAnimation>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </TextBlock.Triggers>
            </TextBlock>              
        </DataTemplate>
    </Window.Resources>
    <Grid DataContext="{Binding Path=Model}">
        <StackPanel>           
            <dg:DataGrid Name="_grid" Height="100" AutoGenerateColumns="False" MinColumnWidth="100" SelectionUnit="Cell" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Path=Tickers}">
                <dg:DataGrid.Columns>
                    <dg:DataGridTextColumn Header="Ticker" Binding="{Binding Path=Name}" Width="100" />
                    <dg:DataGridTemplateColumn Header="Price" CellTemplate="{StaticResource BlinkCellTemplate}" Width="100"/>
                </dg:DataGrid.Columns>
            </dg:DataGrid>
            <Button x:Name="button" Click="button_Click" Content="Press Me"></Button>
        </StackPanel>
    </Grid>
</Window>
public partial class Window6 : Window
    {
        Model6 model = new Model6();
        public Window6()
        {
            InitializeComponent();
            DataContext = this;
            Init();
        }
        public void Init()
        {
            model.Tickers.Add(new Ticker("VOD",100.00));
            model.Tickers.Add(new Ticker("APP", 70.00));
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            foreach (Ticker ticker in model.Tickers)
            {
                ticker.Price = Tick(ticker.Price);
            }
        }
        public Model6 Model
        {
            get { return model; }
        }
        Random random = new Random();
        private double Tick(double value)
        {
            int sign = random.Next(-1, 2);
            double priceChange = 0;
            if(sign!=0)
            {
                priceChange = Math.Round(sign * value * 0.005 * random.Next(0, 10),4);
            }            
            return value + priceChange;
        }
    }
    public class Model6
    {
        private ObservableCollection<Ticker> tickers = new ObservableCollection<Ticker>();
        public ObservableCollection<Ticker> Tickers
        {
            get { return this.tickers; }
        }
    }
    public class Ticker : INotifyPropertyChanged
    {
        private string name;
        private double price;
        public Ticker(string name, double price)
        {
            this.name = name;
            this.price = price;
        }
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged(this, "Name");
            }
        }
        public double Price
        {
            get { return price; }
            set
            {
                price = value;
                OnPropertyChanged(this, "Price");
            }
        }
        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(object sender, string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }  

Friday, 13 August 2010

How to run WPF (XBAP) application in Google Chrome

  • Install Firefox Mozilla (yes we're talking about Chrome here.. )
  • Add C:\Program Files\Mozilla Firefox to environment variable PATH 

Thursday, 12 August 2010

WPF Binding Example and CustomConverter

<Window x:Class="WpfTable.Window3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfTable"    
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="Window3" Height="226" Width="483">
    
    <Window.Resources>
        <local:ColorConverter1 x:Key="colorConverter" />
    </Window.Resources>
    
    <Grid DataContext="{Binding Path=WindowViewModel}">
        <StackPanel>
            <Grid Name="grid1" DataContext="{Binding Path=Player}">
                
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="150"/>
                    <ColumnDefinition Width="150"/>
                    <ColumnDefinition Width="150"/>
                </Grid.ColumnDefinitions>
                
                <Label Content="FirstName" Grid.Column="0" Grid.Row="0"/>
                <Label Content="LastName" Grid.Column="0" Grid.Row="1"/>
                <Label Content="PositionName" Grid.Column="0" Grid.Row="2"/>
                
                <TextBox Text="{Binding Path=FirstName}" Grid.Column="1" Grid.Row="0"/>
                <TextBox Text="{Binding Path=LastName}" Grid.Column="1" Grid.Row="1"/>
                <TextBox Text="{Binding Path=Position}" Grid.Column="1" Grid.Row="2"/>                
                
                <TextBlock Name="label1" Text="{Binding Path=FirstName}" Grid.Column="2" Grid.Row="0"/>
                <TextBlock Name="label2" Text="{Binding Path=LastName}" Grid.Column="2" Grid.Row="1"/>
                <TextBlock Name="label3" Text="{Binding Path=Position}" Grid.Column="2" Grid.Row="2"/>
                
            </Grid>
            
            <StackPanel Orientation="Horizontal">
                <Button x:Name="GreenButton" Background="Green" Margin="5,5,5,5" Width="50" Height="20" Click="GreenButton_Click"/>                
                <Button x:Name="YellowButton" Background="Yellow" Margin="5,5,5,5" Width="50" Height="20" Click="YellowButton_Click"/>
                <Button x:Name="RedButton" Background="Red" Margin="5,5,5,5" Width="50" Height="20" Click="RedButton_Click"/>
            </StackPanel>
            
            <Grid>
                <Border Width="50" Background="Black" CornerRadius="10" BorderBrush="Gray" BorderThickness="2">
                    <StackPanel>
                        <StackPanel.Resources>
                            <Style TargetType="{x:Type Ellipse}">
                                <Setter Property="Width" Value="20" />
                                <Setter Property="Height" Value="20" />
                                <Setter Property="Fill" Value="LightGray" />
                                <Setter Property="Stroke" Value="Gray" />
                                <Setter Property="StrokeThickness" Value="2" />
                                <Setter Property="Margin" Value="4" />
                            </Style>
                        </StackPanel.Resources>
                        <Ellipse Fill="{Binding Green,
                                        Converter={StaticResource colorConverter}, 
                                        ConverterParameter=GREEN}"/>
                        <Ellipse Fill="{Binding Yellow,
                                        Converter={StaticResource colorConverter}, 
                                        ConverterParameter=YELLOW}"/>
                        <Ellipse Fill="{Binding Red,
                                        Converter={StaticResource colorConverter}, 
                                        ConverterParameter=RED}"/>
                    </StackPanel>
                </Border>
            </Grid>
            
        </StackPanel>        
    </Grid>
</Window>
namespace WpfTable
{
    public partial class Window3 : Window
    {
        private WindowViewModel _windowViewModel = new WindowViewModel();
        public Window3()
        {
            InitializeComponent();
        }
        public WindowViewModel WindowViewModel
        {
            get { return _windowViewModel; }
        }
        private void RedButton_Click(object sender, RoutedEventArgs e)
        {
            _windowViewModel.Red = !_windowViewModel.Red;
        }
        private void YellowButton_Click(object sender, RoutedEventArgs e)
        {
            _windowViewModel.Yellow = !_windowViewModel.Yellow;
        }
        private void GreenButton_Click(object sender, RoutedEventArgs e)
        {
            _windowViewModel.Green = !_windowViewModel.Green;
        }
    }
    public class WindowViewModel : DependencyObject
    {
        public WindowViewModel()
        {
            Player = new Player();
            Player.FirstName = "Michael";
            Player.LastName = "Jordan";
            Player.Position = "SG";
        }
        public static readonly DependencyProperty _redProperty = DependencyProperty.Register("Red", typeof(bool), typeof(WindowViewModel), new PropertyMetadata(false));
        public bool Red
        {
            get { return (bool)GetValue(_redProperty); }
            set { SetValue(_redProperty, value); }
        }
        public static readonly DependencyProperty _yellowProperty = DependencyProperty.Register("Yellow", typeof(bool), typeof(WindowViewModel), new PropertyMetadata(false));
        public bool Yellow
        {
            get { return (bool)GetValue(_yellowProperty); }
            set { SetValue(_yellowProperty, value); }
        }
        public static readonly DependencyProperty _greenProperty = DependencyProperty.Register("Green", typeof(bool), typeof(WindowViewModel), new PropertyMetadata(false));
        public bool Green
        {
            get { return (bool)GetValue(_greenProperty); }
            set { SetValue(_greenProperty, value); }
        }
        public Player Player { get; set; }
    }
    public class Player : DependencyObject
    {
        public static DependencyProperty FirstNameProperty =
           DependencyProperty.Register("FirstName", typeof(string),
                                       typeof(Player));
        public string FirstName
        {
            get { return (string)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }
        public static DependencyProperty LastNameProperty =
           DependencyProperty.Register("LastName", typeof(string),
                                       typeof(Player));
        public string LastName
        {
            get { return (string)(GetValue(LastNameProperty)); }
            set { SetValue(LastNameProperty, value); }
        }
        public static DependencyProperty PositionProperty =
           DependencyProperty.Register("Position", typeof(string),
                                       typeof(Player));
        public string Position
        {
            get { return (string)(GetValue(PositionProperty)); }
            set { SetValue(PositionProperty, value); }
        }
    }
    public class ColorConverter1 : IValueConverter
    {
        public enum Lights
        {
            GREEN,
            YELLOW,
            RED
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool state = (bool)value;
            Lights light = (Lights)Enum.Parse(typeof(Lights), (string)parameter);
            if (state)
            {
                switch (light)
                {
                    case Lights.GREEN:
                            return new SolidColorBrush(Colors.Green);
                    case Lights.YELLOW:
                            return new SolidColorBrush(Colors.Yellow);
                    case Lights.RED:
                            return new SolidColorBrush(Colors.Red);
                }
            }
            return new SolidColorBrush(Colors.White);
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

Wednesday, 11 August 2010

Google Web Toolkit (GWT) MVP Example

google-web-toolkit-gwt-mvp-example

WPF DataTable with custom column header

<Window x:Class="WpfTable.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="WPF Tables" Height="309" Width="524">
    
    <Window.Resources>
        <DataTemplate x:Key="OverwriteHeaderTemplate">
            <StackPanel>
                <TextBlock Grid.Column="0" Grid.Row="0" HorizontalAlignment="Center" Text="{Binding Path=ColumnName}"/>
                <TextBox x:Name="overwriteText" Grid.Column="0" Grid.Row="1" Text="{Binding Path=OverwriteText}" MinWidth="30" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=GridViewColumnHeader},Path=ActualWidth}" IsEnabled="False"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    
    <Grid>
        <StackPanel>
            <Grid Background="AliceBlue">
                <Label Content="Basic Table"/>
                <Button Content="Load Data" Margin="5,5,5,5" Click="Button_Click" HorizontalAlignment="Right"/>
            </Grid>            
            <ListView x:Name="listView1" Height="100" ItemsSource="{Binding Path=DataTable}" Background="WhiteSmoke" SelectionChanged="listView1_SelectionChanged" ToolTip="Click to Remove Row" GridViewColumnHeader.Click="listView1_Click">
                <ListView.View>
                    <GridView x:Name="gridView1" ColumnHeaderTemplate="{StaticResource OverwriteHeaderTemplate}">
                        <GridView.Columns>
                            <GridViewColumn Header="Number" DisplayMemberBinding="{Binding Path=Number}" Width="100"/>
                            <GridViewColumn Header="Text" DisplayMemberBinding="{Binding Path=Text}" Width="100"/>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>
            <Grid Background="AliceBlue">
                <Label Content="Copy Table"/>
                <Button Content="Copy with Overwrites" Margin="5,5,5,5" Click="Button_Click_1" HorizontalAlignment="Right"/>
            </Grid>
            <ListView x:Name="listView2" Height="100" ItemsSource="{Binding Path=DataTable2}" Background="WhiteSmoke">
                <ListView.View>
                    <GridView x:Name="gridView2">
                        <GridView.Columns>
                            <GridViewColumn Header="Number" DisplayMemberBinding="{Binding Path=Number}" Width="100"/>
                            <GridViewColumn Header="Text" DisplayMemberBinding="{Binding Path=Text}" Width="100"/>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    </Grid>
</Window>
public partial class Window2 : Window
    {
        private DataTable dataTable = new DataTable();
        private DataTable dataTable2 = new DataTable();
        Dictionary<string, Overwrite> _overwriteColumns = new Dictionary<string, Overwrite>();
        public Window2()
        {
            Init();
            InitializeComponent();            
        }
        private void Init()
        {
            dataTable = new DataTable();
            dataTable.Columns.Add("Number", typeof(int));
            dataTable.Columns.Add("Text", typeof(string));            
            dataTable2 = new DataTable();
            dataTable2.Columns.Add("Number", typeof(int));
            dataTable2.Columns.Add("Text", typeof(string));            
        }
        public DataTable DataTable
        {
            get
            {                
                return dataTable;
            }
        }
        public DataTable DataTable2
        {
            get
            {
                return dataTable2;
            }
        }
        private DataTable GetDataTable()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Number", typeof(int));
            dataTable.Columns.Add("Text", typeof(string));            
            DataRow row = dataTable.NewRow();
            int nextRow = dataTable.Rows.Count + 1;
            row["Number"] = nextRow;
            row["Text"] = string.Format("Row {0}", nextRow);            
            dataTable.Rows.Add(row);
            row = dataTable.NewRow();
            nextRow = dataTable.Rows.Count + 1;
            row["Number"] = nextRow;
            row["Text"] = string.Format("Row {0}", nextRow);            
            dataTable.Rows.Add(row);
            return dataTable;
        }
        private void FillListView(DataTable dt)
        {
            dataTable = null;
            dataTable = new DataTable();
            _overwriteColumns.Clear();
            gridView1.Columns.Clear();
            dataTable.BeginLoadData();
            foreach (DataColumn column in dt.Columns)
            {
                dataTable.Columns.Add(column.ColumnName, column.DataType);
            }
            foreach (DataRow row in dt.Rows)
            {
                dataTable.ImportRow(row);
            }
            dataTable.EndLoadData();
            listView1.ItemsSource = dataTable.DefaultView;
            DataTemplate dataTemplate = (DataTemplate)this.FindResource("OverwriteHeaderTemplate");
            foreach (DataColumn column in dt.Columns)
            {
                _overwriteColumns.Add(column.ColumnName, new Overwrite(column.ColumnName, string.Empty));
                GridViewColumn c = new GridViewColumn();
                c.Header = _overwriteColumns[column.ColumnName];
                c.DisplayMemberBinding = new Binding(column.ColumnName);
                c.HeaderTemplate = dataTemplate;
                gridView1.Columns.Add(c);
            }
        }
        private string GetValue(DataRow row, DataColumn column)
        {
            string result = string.Empty;
            if (row.IsNull(column.ColumnName))
            {
                result = "NULL";
            }
            else if (column.DataType == typeof(string))
            {
                result = string.Format("'{0}'", ((string)row[column.ColumnName]).Trim());
            }
            else if (column.DataType == typeof(int))
            {
                result = ((int)row[column.ColumnName]).ToString();
            }
            else if (column.DataType == typeof(float))
            {
                result = ((float)row[column.ColumnName]).ToString();
            }
            else if (column.DataType == typeof(bool))
            {
                bool v = (bool)row[column.ColumnName];
                result = (v) ? "1" : "0";
            }
            else if (column.DataType == typeof(DateTime))
            {
                result = string.Format("'{0}'", ((DateTime)row[column.ColumnName]).ToString("yyyy/MM/dd HH:mm:ss.fff"));
            }
            return result;
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FillListView(GetDataTable());
        }
        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(e.AddedItems.Count>0)
            {
                DataRowView rowView = (DataRowView)e.AddedItems[0];
                DataRow row = rowView.Row;                 
                dataTable.Rows.Remove(row);
            }
        }
        private childItem FindVisualChild<childItem>(DependencyObject obj)
            where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
        internal class Overwrite
        {
            public static int TYPE_NORMAL = 0;
            public static int TYPE_OVERWRITE = 1;
            public Overwrite(string columnName, string overwriteText)
            {
                this.ColumnName = columnName;
                this.OverwriteText = overwriteText;
                this.ColumnType = TYPE_NORMAL;
            }
            public string ColumnName { get; set; }
            public string OverwriteText { get; set; }
            public int ColumnType { get; set; }
        }
        private void listView1_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader header = e.OriginalSource as GridViewColumnHeader;
            Overwrite overwrite = (Overwrite)header.Column.Header;
            ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(header);
            DataTemplate dataTemplate = myContentPresenter.ContentTemplate;
            var overwriteTextBox = (TextBox)dataTemplate.FindName("overwriteText", myContentPresenter);
            if (header.Background == Brushes.LightSalmon)
            {
                overwrite.ColumnType = Overwrite.TYPE_NORMAL;
                header.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFD4D0C8"));
                overwriteTextBox.IsEnabled = false;
            }
            else
            {
                overwrite.OverwriteText = overwriteTextBox.Text;
                overwrite.ColumnType = Overwrite.TYPE_OVERWRITE;
                header.Background = Brushes.LightSalmon;
                overwriteTextBox.IsEnabled = true;
            } 
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            dataTable2.Clear();
            foreach (DataRow row in dataTable.Rows)
            {
                DataRow row2 = dataTable2.NewRow();
                foreach (DataColumn column in dataTable.Columns)
                {
                    if (_overwriteColumns[column.ColumnName].ColumnType == Overwrite.TYPE_OVERWRITE)
                    {
                        string overwriteText = _overwriteColumns[column.ColumnName].OverwriteText;
                        row2[column.ColumnName] = overwriteText;
                    }
                    else if (_overwriteColumns[column.ColumnName].ColumnType == Overwrite.TYPE_NORMAL)
                    {
                        row2[column.ColumnName] = row[column.ColumnName];
                    }
                }
                dataTable2.Rows.Add(row2);
            }
        }
    }