I'm trying to cancel an edit when a bool returns as false. The bool is set to false once I've iterated through the selected cells and done some calculations. This is in the CellEditEnding function, but I'm using EventTrigger interactivity so it's all MVVM and I don't have the datagrid object to actually do a CancelEdit call when this bool is false.
Is there any way I can cancel an edit using MVVM? When I lose focus from the cell, it is still white...
This is how I've got round it at the moment... don't like it though...
In the code I do this... I just don't like doing this in the viewmodel... kinda breaks MVVM
public void CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
bool isSuccess = true;
if (e.EditAction == DataGridEditAction.Commit)
{
if (e.EditingElement is TextBox cellTextEdit && cellTextEdit.Text != string.Empty)
{
for (int iSelected = 0; iSelected < SelectedGridCellCollection.Count; ++iSelected)
{
if (!isSuccess)
{
e.Cancel = true;
// Only "non" MVVM here, but if there is another way to do this then I'd
// be surprised...
DataGrid dg = sender as DataGrid;
dg.CancelEdit();
}
}
}
}
}
In the XAML
<DataGrid Name="dataGrid" Width="550" ItemsSource="{Binding ObjSource}"
CanUserSortColumns="False" CanUserAddRows="false"
HorizontalAlignment="Stretch"
VerticalScrollBarVisibility="Auto"
utils:DataGridSelectedCellsBehavior.SelectedCells="{Binding SelectedGridCellCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False"
Background="{StaticResource ResourceKey=Polour}"
SelectionUnit="Cell"
RowHeaderWidth="0"
RowStyle="{StaticResource DataGridRowStyle}"
AlternationCount="2"
FontFamily="{StaticResource ResourceKey=Light}"
CanUserResizeColumns="False" CanUserReorderColumns="False">
<DataGrid.Resources>
<Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="{StaticResource ResourceKey=Polour}"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="BorderBrush" Value="{StaticResource ResourceKey=Solour}"/>
<Setter Property="BorderThickness" Value="0,0,0,1"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Margin" Value="5 0 5 0"/>
<Setter Property="Height" Value="30"/>
<Setter Property="Width" Value="Auto"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="ll" Binding="{Binding Id}" IsReadOnly="True"></DataGridTextColumn>
</DataGrid.Columns>
<i:Interaction.Triggers>
<i:EventTrigger EventName="CellEditEnding">
<i:CallMethodAction TargetObject="{Binding}" MethodName="CellEditEnding"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>