简体   繁体   中英

How to bind Row Header in wpf datagrid?

In my project i want datagrid row header values like outlook calendar. For assuming that is 9.00, 9.30, 10.00, 10.30.... But its not fixed one, it may vary,.. 9.00 pm, 10.00 pm.

i am using two TextBlock for this and i got almost same shape too. but my values are fixed one that is 1-00, 1-00,1-00, 1-00,1-00, 1-00,........

My Code-

<DataGrid AutoGenerateColumns="False" Height="560" HorizontalAlignment="Left" Margin="30,54,0,0" Name="myDataGrid" VerticalAlignment="Top" Width="884" MouseDoubleClick="myDataGrid_MouseDoubleClick" IsEnabled="True" SelectionUnit="Cell">
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                        <TextBlock Text="1" Foreground="#9493CF" FontSize="16" />
                        <TextBlock Text="00" Foreground="#9493CF" />
                    </StackPanel>
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
            <DataGrid.ContextMenu>
                <ContextMenu x:Name="LeftClickMenu">
                    <MenuItem Header="New Appointment" Click="MenuItem_Click"/>
                    <!--<MenuItem Header="Save"/>
                    <MenuItem Header="Print"/>-->
                    <Separator/>
                    <MenuItem Header="Exit"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>

What I want -

在此输入图像描述

What I Got -

在此输入图像描述

You can specify negative top margin on second textBlock:

 <TextBlock Text="00" Foreground="#9493CF" Margin="1,-5,0,0"/> 

Output with negative top margin:

在此输入图像描述

Output without margin:

在此输入图像描述

Update :

In case you want header to be customizable, you need to have one property in your model class ( object representing row ) say Time which will be different for different rows. For first row Time value will be 9, second 10 and so on.

Then you can bind to that property like this:

 <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock Text="{Binding Path=DataContext.Time, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridRowHeader}}" Foreground="#9493CF" FontSize="16" /> <TextBlock Text="00" Foreground="#9493CF" /> </StackPanel> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM