0

I am creating a column in my DataGrid with

<DataGridTextColumn Header="Deploy" Binding="{Binding Deploy}" Width="100" IsReadOnly="True" CanUserSort="False"/>

In my code, I am adding rows to the columns in my grid using

Public Structure MyRow
    Public Property Deploy As String
End Structure



MyGrid.Items.Add(New MyRow With {.Deploy= "Unlimited"})

What I really want to be doing, is in this Deploy field, I want to display one of two buttons dependent on a value. If I have the value 0, I want to display

<Button Grid.Column="3" Padding="0" Content="A" Margin="5,8,5,12" Height="50" TextBlock.TextAlignment="Center" />

And if I have the value -1 I want to display

<Button Grid.Column="3" Padding="0" Content="B" Margin="5,8,5,12" Height="50" TextBlock.TextAlignment="Center" />

Any help as to how would be appreciated! I've tried using a CellTemplateSelector

<Page.Resources>
    <DataTemplate x:Key="ATemplate">
        <Button Grid.Column="3" Padding="0" Content="A" Margin="5,8,5,12" Height="50" TextBlock.TextAlignment="Center" />
    </DataTemplate>
    <DataTemplate x:Key="BTemplate">
        <Button Grid.Column="3" Padding="0" Content="B" Margin="5,8,5,12" Height="50" TextBlock.TextAlignment="Center" />
    </DataTemplate>
</Page.Resources>


...
<DataGridTemplateColumn Header="A" Width="60" CanUserSort="False" CellTemplateSelector="{StaticResource ButtonTemplateSelector}" />
...

But then I don't know how I could then apply this template when I am adding a row to the DataGrid

Thanks in advance

Navvy
  • 237
  • 3
  • 9
  • 23

1 Answers1

0

Just implement your logic in the ButtonTemplateSelector:

Public Class ButtonTemplateSelector
    Inherits DataTemplateSelector

    Public Property ATemplate As DataTemplate
    Public Property BTemplate As DataTemplate

    Public Overrides Function SelectTemplate(item As Object, container As DependencyObject) As DataTemplate

        If item IsNot Nothing Then
            Dim myRow = CType(item, MyRow)
            If myRow.Deploy Is "0" Then
                Return ATemplate
            Else
                Return BTemplate
            End If
        End If

        Return MyBase.SelectTemplate(item, container)
    End Function

End Class

XAML:

<DataGridTemplateColumn Header="A" Width="60" CanUserSort="False" >
    <DataGridTemplateColumn.CellTemplateSelector>
        <local:ButtonTemplateSelector ATemplate="{StaticResource ATemplate}"
                                      BTemplate="{StaticResource BTemplate}" />
    </DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thanks! That's great, turns out I'd been close just wasn't using the selector quite right! – Navvy May 18 '20 at 07:53