I have to show a list where each item will be validated. I am subscribed to Validation.ErrorEvent
on a top level to monitor for children.
When I remove item with validation error from list this event is not rised.
In example below I have 3 TextBox
on screen, each is bound to int
property. Entering wrong value will fire event (Title
is changed to "+"
), fixing value afterwards will fire event once (Title
is changed to "-"
).
However removing TextBox
while having error will not rise event (to clean up) and Title
stay "+"
:
How can I fix that? Ideally I want that this event is automatically rised before removing happens.
Please note: in real project there is complex hierarchy of view models, solutions like "set Title
in delete method" would require monitoring for sub-views and propagating that info through all hierarchy, which I'd like to avoid. I'd prefer view-only solution.
MCVE:
public partial class MainWindow : Window
{
public ObservableCollection<VM> Items { get; } = new ObservableCollection<VM> { new VM(), new VM(), new VM() };
public MainWindow()
{
InitializeComponent();
AddHandler(Validation.ErrorEvent, new RoutedEventHandler((s, e) =>
Title = ((ValidationErrorEventArgs)e).Action == ValidationErrorEventAction.Added ? "+" : "-"));
DataContext = this;
}
void Button_Click(object sender, RoutedEventArgs e) => Items.RemoveAt(0);
}
public class VM
{
public int Test { get; set; }
}
xaml:
<StackPanel>
<ItemsControl ItemsSource="{Binding Items}" Height="200">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Test, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Content="Remove first" Click="Button_Click" />
</StackPanel>