I have created a DataGrid in WPF from a DataTable with AutoGenerateColumns = true
. In the VM I have a command property for adding and deleting columns which manipulates the underlying DataTable.
When I call AddColumn
from the main XAML window via Command="{Binding AddColumn}"
it works as expected but when I call the RemoveColumn from a resource file with a context menu it calls the command property (im able to step through the code) but does not update the Grid.
<MenuItem Header="Delete" Command="{Binding Source={StaticResource AppViewModel}, Path=DeleteColumn}" CommandParameter="{Binding}" />
I now updated both commands to only set the DataTable to null, ie Dt = null
and for the AddColumn this works as expected and removed the Grid and columns but for the RemoveColumn it does nothing... I also see no errors in the output window in regard to binding and when stepping through the code the property is called. I also tried to set the column to invisible which also did not work.
UPDATE
I call the DeleteColumn from the following (simplified) code in a resources file.
<Style x:Key="ColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="VerticalContentAlignment" Value="Center" />
<Style.Triggers>
<DataTrigger Binding="{Binding Content, ConverterParameter=*, Converter={StaticResource AfterDashConverter}, RelativeSource={RelativeSource self}}" Value="Green">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Command="{Binding Source={StaticResource AppViewModel}, Path=DeleteColumn}" />
</ContextMenu>
</Grid.ContextMenu>
<DataGridColumnHeader x:Name="PART_FillerColumnHeader" IsHitTestVisible="False"/>
<ItemsPresenter/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
The commands are very simple, the AddColumn works as its directly in my main view and the DeleteColumn does not as its in the above resource file. I have checked the commands fire properly.
AddColumn = new RelayCommand(_ =>
{
Dt = null;
}, true);
DeleteColumn = new RelayCommand(column =>
{
Dt = null;
}, true);
the main issue was my resource was creating a new viewmodel so it was not calling / impacting the VM instance that my view was dependent on. To fix this I needed to set the
DataContext
of myContextMenu
parent control (which was a grid) as follows:If you just call the following it will create a new instance of your ViewModel and use that: