Search code examples
wpfxamluniformgrid

How can I get a datatemplate to fill uniform grid cell?


Here is my xaml. I need the red grid to fill the entire cell.

<UserControl x:Class="Atelis.Tcc.Client.CheckList_TileView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300"
         DataContext="{Binding Model}">
<ListBox ItemsSource="{Binding Checks}" SelectedItem="{Binding SelectedCheck}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns=" 3 "/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <Grid.InputBindings>
                    <MouseBinding Gesture="LeftDoubleClick" Command="{Binding Path=DataContext.OpenSelectedCheck, ElementName=TileView}"/>
                </Grid.InputBindings>
                <StackPanel>
                    <TextBlock Text="{Binding CheckRoot.CheckNum}"/>
                    <TextBlock Text="{Binding CheckRoot.CheckDate}"/>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

My goal is to allow the user to click anywhere in the cell to perform the InputBinding command. So if there is another way to accomplish that goal, that will also suffice as an answer.

enter image description here


Solution

  • if I got you correct then it looks like your cells are not fully stretched in the listbox

    so setting HorizontalContentAlignment="Stretch" & VerticalContentAlignment="Stretch" will do the trick

    <ListBox HorizontalContentAlignment="Stretch" 
             VerticalContentAlignment="Stretch"
             ItemsSource="{Binding Checks}" 
             SelectedItem="{Binding SelectedCheck}" >
    

    Alternative approach

    <ListBox ItemsSource="{Binding Checks}" 
             SelectedItem="{Binding SelectedCheck}" >
        <ListBox.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <ContentPresenter />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.Resources>
    

    this approach will also help you remove the selected background (usually blue) if you may want to remove that too