Search code examples
c#wpflistviewgridviewcelltemplate

Add Custom Template To ListView - GridView WPF?


I currently have this XAML Code:

<ListView x:Name="listFeedSearch" Margin="-548.856,95.333,0,7.667" HorizontalAlignment="Left" Width="542.5" RenderTransformOrigin="0.5,0.5" ItemsSource="{Binding SearchCollection}">
    <ListView.RenderTransform>
        <TransformGroup>
            <ScaleTransform/>
            <SkewTransform/>
            <RotateTransform/>
            <TranslateTransform/>
        </TransformGroup>
    </ListView.RenderTransform>
    <ListView.View>
        <GridView>
            <GridViewColumn Width="150" Header="Feed Name" x:Name="listFeedSearchName" DisplayMemberBinding="{Binding FeedName}"  />
            <GridViewColumn Width="280" Header="Feed Address" x:Name="listFeedSearchAddress" DisplayMemberBinding="{Binding FeedUrl}" />
            <GridViewColumn Width="100" Header=" " x:Name="listFeedSearchSelect" />
        </GridView>
    </ListView.View>
</ListView>

What I want to do is have listFeedSearchSelect have a Button in the cell for every record.

What I had tried to do is, but didn't work, all it did was display as empty cell:

<GridViewColumn Header=" " Width="100" x:Name="listFeedSearchSelect">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
                <Button Content="Select" />
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

Can anyone help me out here, thanks.


Solution

  • Try setting up your template as a resource. Like so:

    <Window.Resources>
        <DataTemplate x:Key="SelectButtonColumnDataTemplate">
            <Button Content="Select" Command="{Binding SelectItemCommand}" />
        </DataTemplate>
    </Window.Resources>
    
    <ListView x:Name="listFeedSearch" HorizontalAlignment="Left" Width="542.5" RenderTransformOrigin="0.5,0.5" ItemsSource="{Binding SearchCollection}">
        <ListView.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>                
                <RotateTransform/>                
                <TranslateTransform/>            
                </TransformGroup>        
                </ListView.RenderTransform>        
        <ListView.View>            
            <GridView>                
                <GridViewColumn Width="150" Header="Feed Name" x:Name="listFeedSearchName" DisplayMemberBinding="{Binding FeedName}"  />                
                <GridViewColumn Width="280" Header="Feed Address" x:Name="listFeedSearchAddress" DisplayMemberBinding="{Binding FeedUrl}" />                
                <GridViewColumn Width="100" Header=" " CellTemplate="{StaticResource SelectButtonColumnDataTemplate}" />            
            </GridView>        
            </ListView.View>    
    </ListView>