I have a datagrid in which I want to add a button to each line. This button should have another function depending on a condition. The datagrid consists of a list of some files that can be installed or, if already present, uninstalled using the button. Therefore the button should be called either "Install" or "Uninstall".
I created the following xaml
...
<Grid.Resources>
<local:ButtonTemplateSelector x:Key="buttonTemplateSelector">
<local:ButtonTemplateSelector.InstallButtonTemplate>
<DataTemplate>
<Button x:Name="btn_installSnippet" Click="btn_installSnippet_Click">Install</Button>
</DataTemplate>
</local:ButtonTemplateSelector.InstallButtonTemplate>
<local:ButtonTemplateSelector.UninstallButtonTemplate>
<DataTemplate>
<Button x:Name="btn_uninstallSnippet" Click="btn_uninstallSnippet_Click">Uninstall</Button>
</DataTemplate>
</local:ButtonTemplateSelector.UninstallButtonTemplate>
</local:ButtonTemplateSelector>
</Grid.Resources>
...
<DataGrid x:Name="dataGrid_newViews" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="148" Margin="40,152,0,0" VerticalAlignment="Top" Width="685" AutoGenerateColumns="True" SelectedCellsChanged="Datagrid_SelectedCellsChanged" CanUserAddRows="false" Grid.ColumnSpan="2">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Button" CellTemplateSelector="{StaticResource buttonTemplateSelector}" />
</DataGrid.Columns>
</DataGrid>
In my main code, I have created the following:
public class ButtonTemplateSelector : DataTemplateSelector
{
public DataTemplate InstallButtonTemplate { get; set; }
public DataTemplate UninstallButtonTemplate { get; set; }
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
return InstallButtonTemplate;
}
}
Here I am completely stuck, on how to get a value from the row (from datagrid binding), to write the condition if InstallButtonTemplate
or UninstallButtonTemplate
should be returned.
You have pretty much done all the work, one piece that is missing is to cast your
object item
parameter to the data type of the item in the collection you are binding to like this: