-->

Tuesday, May 3, 2016

Get the Cell value of selected Row From DataGrid in WPF

In this article i will show you, how to get the cell value from datagrid in WPF. We all know that dataGrid is use for storing data in a tabular format. By using AutoGenerateColumns we will show our table columns in it.  If you want to show your customized columns in it the  add DataGridTemplate Column.  In it we have cell template, by using this we can design our dataGrid cells. In the first DataTemplate i will take a button control through it we can show the cell value of dataGrid.


<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid Name="grid1" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="b1" Click="b1_Click" Content="click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}" />
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>

            </DataGrid.Columns>
         
        </DataGrid>
    </Grid>
</Window>

In this XAML code we have a Id and Name property which is bind with public property of student class.

using System;
using System.Windows;

namespace WpfApplication13
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
           grid1.ItemsSource = Student.getStudent();
        }

        private void b1_Click(object sender, RoutedEventArgs e)
        {
            Student st = grid1.SelectedItem as Student;
            string studentid = Convert.ToString(st.Id);
            string studentName = st.Name;
            MessageBox.Show(studentid + " " + studentName);

        }
    }
}

using System.Collections.ObjectModel;

namespace WpfApplication13
{
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public static ObservableCollection<Student> getStudent()
        {
            var student = new ObservableCollection<Student>();
            student.Add(new Student() { Id = 1, Name = "Jacob" });
            student.Add(new Student() { Id = 2, Name = "Bill" });
            return student;



        }
    }
}

Wednesday, April 27, 2016

Bind ComboBox with Enum Type in WPF


In this article i will show you, How to Bind ComboBox with Enum properties.  Enum is a type, which is used to fix no of values like Sunday, Monday, Tuesday...etc.). By using XAML, you can add static resources for enumeration. In WPF We have a ObjectDataProvider for enumeration. Lets check the code.

XAML Code :

<Window x:Class="WpfApplication1212.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local1="clr-namespace:WpfApplication1212"
        xmlns:codeg="clr-namespace:System;assembly=mscorlib"
        Title="Window2" Height="300" Width="300">
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type codeg:Enum}" x:Key="myenu">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local1:week1" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource myenu}}" />
    </Grid>
</Window>

Enumeration code 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1212
{
    class Order
    {
    }
    public enum week1
    {
        sun,mon,tue,wed,
    }
}

Thursday, April 21, 2016

WPF: How to take image and button control in WPF ListView

Good Morning: Today i will teach you how to add controls in ListView. In this article i will add button control and image control. According to my previous article image control bind with source, so  it required source for binding, so i have create a ImageSource public property in class. We know that ListView contain only single view i.e GridView. A GridView contain rows and column , also we can say that cell is a combination of rows and column. In this article i have create CellTemplate.  Inside the CellTemplate we have a Data Template. In the Code behind page, we have a class with one property i.e "ImageSource", which is used for Image binding. Add a list control with class type, in it we have two images. Lets check the code and their output
XAML Code
<Window x:Class="WpfApplication11.ImageinListview"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ImageinListview" Height="300" Width="300">
    <Grid>
        <ListView Name="List1" MouseDoubleClick="getSelectedItem">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Action">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Click Me" Click="Button_Click"/>                              
                            </DataTemplate>                        
                           
                        </GridViewColumn.CellTemplate>                      
                    </GridViewColumn>
                    <GridViewColumn Header="Image">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="{Binding ImageSource}" Width="100" Height="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>

                    </GridViewColumn>

                </GridView>
            </ListView.View>        
           
        </ListView>
       
    </Grid>
</Window>

Code Behind Code:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for ImageinListview.xaml
    /// </summary>
    public partial class ImageinListview : Window
    {
        public ImageinListview()
        {
            InitializeComponent();
            bindlist();
        }

        private void bindlist()
        {
           // throw new NotImplementedException();
            List<imgs> listr = new List<imgs>();
            listr.Add(new imgs() { ImageSource = "/imag/11.png" });
            listr.Add(new imgs() { ImageSource = "/imag/bleaching.jpg" });
            List1.ItemsSource = listr;


        }
        private void getSelectedItem(object sender, MouseButtonEventArgs e)
        {
            imgs imgh = List1.SelectedItems[0] as imgs;
            MessageBox.Show(imgh.ImageSource);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
    
        }
    }
    public class imgs
    {
        public string ImageSource { get; set; }
    }
}
Code generate the following output

WPF: How to take image and button control in WPF ListView


Saturday, April 16, 2016

BackgroundWorker Example in WPF C#

Background Worker is used to do processing in background.  I mean to say that if you have two work and you want to do complete both task at same time then must to use BackgroundWorker class. You can do two task at same time , like in gmail, attach a file with writing some text in the Text. Use this example and see more things about BackgroundWorker class.


XAML Code: 

<Grid>
        <Button Content="Run BackGround Work" HorizontalAlignment="Left" Margin="38,32,0,0" VerticalAlignment="Top" Width="209" Click="Button_Click"/>

        <Label Content="" HorizontalAlignment="Left" Margin="38,68,0,0" VerticalAlignment="Top" Name="processlbl"/>

        <Label Content="" HorizontalAlignment="Left" Margin="217,68,0,0" VerticalAlignment="Top" Name="Completelbl"/>

        <Button Content="Other Task" HorizontalAlignment="Left" Margin="48,157,0,0" VerticalAlignment="Top" Width="199" Click="Button_Click_1"/>

        <TextBox Name="t1" HorizontalAlignment="Left" Height="23" Margin="48,198,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="199"/>

        <Label Content="" HorizontalAlignment="Left" Margin="60,226,0,0" VerticalAlignment="Top" Name="outputlbl"/>

    </Grid>

Code Behind Code:

using System.ComponentModel;
using System.Windows;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker worker = new BackgroundWorker();
        public MainWindow()
        {
            InitializeComponent();
            worker.DoWork += worker_Dowork;
            worker.RunWorkerCompleted += worker_RunworkerCompleted;
        }

        private void worker_RunworkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                Completelbl.Content = "Complete Backgroung Work";
            }
            else
            {
                Completelbl.Content = "Fail";
            }
        }
        private delegate void mydelegate(int i);
        private void displayi(int i)
        {
            processlbl.Content = "Background work:" + i.ToString();
        }
        private void worker_Dowork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                System.Threading.Thread.Sleep(2000);
                if(worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                mydelegate deli = new mydelegate(displayi);
                processlbl.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, deli, i);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            worker.RunWorkerAsync();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            outputlbl.Content = t1.Text;
        }
    }
}

Tuesday, December 22, 2015

Example of Customized TabItem of TabControl in WPF

Customized Tab Item Example:
Tab Item is the item control of Tab control. In this article, I will show you, how to add images, TextBlock and any other control inside TabControl. Also I will show you how to move Tab Control's tabs using buttons like Pre, Next, Get Item of Selected tab. When we press Previous button then next tab move to previous button. Similarly for all buttons. 



<Window x:Class="WpfApplication9.tabcon"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="tabcon" Height="300" Width="300">
    <Grid>
        <!--<TabControl>
            <TabItem Header="First Item">
                <Label Content="Items in the first tab"/>
            </TabItem>
            <TabItem Header="Second Item"/>
            <TabItem Header="Third Item"/>
           
           
        </TabControl>-->
        <DockPanel>
            <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom">
                <Button Name="prebutton" Click="prebutton_Click" Height="36" Width="54">Pre</Button>
                <Button Name="Nextbutton" Click="Nextbutton_Click"  Height="36" Width="54">Next</Button>
                <Button Name="selectbutton" Click="selectbutton_Click"  Height="36" Width="54">select</Button>
            </StackPanel>
            <TabControl Name="sample">
                <TabItem Header="First Item">
                    <Label Content="Content in First tab"/>
                </TabItem>
                <TabItem>
                    <TabItem.Header>
                        <TextBlock Text="Second Tab" Foreground="Red"/>
                    </TabItem.Header>
                </TabItem>
                <TabItem Header="Third Tab"/>
            </TabControl>
           
        </DockPanel>
    </Grid>
</Window>

Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Shapes;

namespace WpfApplication9
{
    /// <summary>
    /// Interaction logic for tabcon.xaml
    /// </summary>
    public partial class tabcon : Window
    {
        public tabcon()
        {
            InitializeComponent();
        }

        private void prebutton_Click(object sender, RoutedEventArgs e)
        {
            int nindex = sample.SelectedIndex - 1;
            if (nindex < 0)
                nindex = sample.Items.Count - 1;
            sample.SelectedIndex = nindex;
        }

        private void Nextbutton_Click(object sender, RoutedEventArgs e)
        {
            int nindex = sample.SelectedIndex + 1;
            if (nindex >= sample.Items.Count)
                nindex = 0;
            sample.SelectedIndex = nindex;
        }

        private void selectbutton_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Selected Tab is:" + (sample.SelectedItem as TabItem).Header);
        }
    }
}

Wednesday, December 16, 2015

Example of Context menu in WPF

Context Menu Introduction:
Context menu means a window appear when we click on right button of mouse on selected Text. Today, we will design context menu with the help of WPF. Here, we will take a Input control with context menu also context menu contain MenuItem.



XAML Code
<Grid>
        <RichTextBox >
            <RichTextBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Command="Cut">
                        <MenuItem.Icon>
                            <Image Source="apple.png"/>
                        </MenuItem.Icon>
                    </MenuItem>
                    <MenuItem Command="Copy">
                        <MenuItem.Icon>
                            <Image Source="grapes.png"/>
                        </MenuItem.Icon>
                    </MenuItem>
                </ContextMenu>              
               
            </RichTextBox.ContextMenu>
                 
           
        </RichTextBox>

    </Grid>
Suppose, your richTextBox is disabled and you want to show context menu on disabled item then use this code:

<RichTextBox IsEnabled="False" ContextMenuService.ShowOnDisabled="True">

© Copyright 2013 Computer Programming | All Right Reserved