Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
SQL
I am new to WPF and in my application I want to insert an image in the one of the columns header with the header text and want to write code on the image OnClick event.

Currently all the column and row data is fetched from database.

C#
newRow = dataInfo.ProcessDataRow(filter, ProcessNames[j], ProcessCaseNames[i]);

  if (newRow != null)
                            {
                                App.Current.Dispatcher.Invoke((Action)(() =>
                                    {
                                        ReportData.Add(newRow);
                                    }));
                            }

xaml code:
C#
<DataGrid ItemsSource="{Binding Path=ReportData, Mode=TwoWay}" SelectedItem="{Binding SelectedRow}" AutoGenerateColumns="True" Grid.Row="1" HorizontalAlignment="Stretch" Name="Datagrid" VerticalAlignment="Stretch" BorderThickness="1" IsReadOnly="True" AlternatingRowremoved="Gainsboro" AlternationCount="2" CanUserReorderColumns="True" BorderBrush="Black" Margin="0,3,0,90" SelectionChanged="Datagrid_SelectionChanged">

Can anyone please assist me how to implement this functionality from code behind.
Posted

You can simple Create one Header style in which u can take one stackpanel which will contain one textblock and one image with appropriate path and add that header style to runtime to that control



XAML Code

HTML
<Window x:Class="PrintingApplication.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">
    <Window.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}" x:Key="imageDataGridRowHeader">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=Columns[1].Header}"/>
                            <Image IsHitTestVisible="True" Height="20" Width="20" VerticalAlignment="Center"  Source="/PrintingApplication;Component/dark_windows_8-wide.jpg"  Margin="0" KeyboardNavigation.IsTabStop="False"/>
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid >
        <DataGrid x:Name="data1" AutoGenerateColumns="True"  ItemsSource="{Binding Path=.}"  Width="500" Height="500" PreviewMouseRightButtonDown="data1_PreviewMouseRightButtonDown_1"></DataGrid>
    </Grid>
</Window>



Code Behind Call



C#
public MainWindow()
       {
           InitializeComponent();
           BindDataToDataGrid();
       }


       private void BindDataToDataGrid()
       {
           DataTable dt = new DataTable();
           dt.Columns.Add("ID");
           dt.Columns.Add("Image");
           dt.Rows.Add("Kartik", "Send");
           dt.Rows.Add("Ashok", "Resend");
           dt.Rows.Add("Paresh", "Report");
           dt.AcceptChanges();

           data1.ItemsSource = dt.DefaultView;

           data1.AutoGeneratingColumn += data1_AutoGeneratingColumn;
       }

       void data1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
       {
           if (Convert.ToString(e.Column.Header) =="Image")
           {
               e.Column.HeaderStyle = FindResource("imageDataGridRowHeader") as Style;
           }
       }
 
Share this answer
 
v2
Comments
Supriya Srivastava 2-Jul-14 4:13am    
Ur code was bit helpful for me to some extend but as I mentioned before I need click event on Image click. I did the below:
<textblock text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=Columns[22].Header}">

<Button Name="btnYieldFilter" Margin="3,0,0,0" Click="btn_Click" >
<Button.Template>
<controltemplate>
<Image IsHitTestVisible="True" Height="10" Width="10" VerticalAlignment="Center" Source="/..Image.png" Margin="0" KeyboardNavigation.IsTabStop="False"/>

</Button.Template>
</Button>
I have added this style in Resource dictionary due to some constraints in my project but his is throwing error as "'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file. Either remove the event handler for the Click event, or add a x:Class attribute to the root element."
so can you please help me how to set click event in code behind or in resource dictionary.

Thanks!!
I wanted something like below (Image Button Click)

C#
<window.resources>
     <style targettype="{x:Type DataGridColumnHeader}" x:key="imageDataGridRowHeader" xmlns:x="#unknown">
         <setter property="Template">
             <setter.value>
                 <controltemplate targettype="{x:Type DataGridColumnHeader}">
                     <stackpanel orientation="Horizontal">
                         <textblock text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=Columns[1].Header}" />

                     <Button x:Name="btnFilter" Margin="3,0,0,0" Content="Content_1">
                         <Button.Template>
                             <controltemplate>
                                 <image ishittestvisible="True" height="10" width="10" verticalalignment="Center" source="/..Image.png" margin="0" keyboardnavigation.istabstop="False" />
                             </controltemplate>
                         </Button.Template>
                     </Button>
                     </stackpanel>
                 </controltemplate>
             </setter.value>
         </setter>
     </style>
 </window.resources>
 <grid></grid>



and in .xaml.cs to have Click event I added below:

C#
void data1_AutoGeneratingColumn(object sender ,DataGridAutoGeneratingColumnEventArgs e)
 { 
             e.Column.HeaderStyle = FindResource("imageDataGridRow <big> Header")as Style;
 EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandle</big>r(btn_Click));

} 
 
Share this answer
 

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