Search code examples
c#avalonia

Hide or edit exception after failed binding or validation in DataGrid in Avalonia


Let's say I have a basic app that gets some data, allows user to edit and save it. I use DataGrid to display that data.

Here's a simple XAML:

<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="using:avaldatepicktest.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
    x:Class="avaldatepicktest.Views.MainWindow"
    x:DataType="vm:MainWindowViewModel"
    Icon="/Assets/avalonia-logo.ico"
    Title="title...">
    <StackPanel>
        <DataGrid ItemsSource="{Binding SomeModels}" AutoGenerateColumns="True">
        </DataGrid>
    </StackPanel>
</Window>

And ViewModel:

public class SomeModel(decimal someNum = 10.0m)
{
    public decimal SomeValue { get; set; } = someNum;
}

public partial class MainWindowViewModel : ViewModelBase
{
    public ObservableCollection<SomeModel> SomeModels { get; }= new ObservableCollection<SomeModel>([
        new SomeModel(),
        new SomeModel(11.0m),
        new SomeModel(5.0m),
    ]);
}

Now, whenever I change data in that table, it is automatically saved and all is fine.

If I enter a wrong value there, I get this exclamation mark:

exclamation mark icon near invalid value

It seems fine as a way to show user that the value is wrong. However if I hover over that exclamation mark I see a nasty exception that end user probably should not see in such form:

Raw exception shown to user

This either should not be displayed at all or be displayed in a nicer way without all these InvalidCastExceptions (something like just "Incorrect number" would be enough) but I haven't found any way to achieve this so far. Is it possible?

I figured I could try to implement INotifyDataErrorInfo in model class which allows me to show nice message if I have empty string in that cell. But if I have a non-empty but non-numeric string there it still shows the same exception.


Solution

  • I am quite unsure if that is the proper solution but the only working way to achieve what I want that I found so far is to wrap SomeModel with a sort of "wrapper" for it that has all it's properties typed as string.

    Something like this:

    public class SomeModel(decimal someNum = 10.0m)
    {
        public decimal SomeValue = someNum;
    }
    
    public class SomeModelWrapper(SomeModel data) : ObservableObject, INotifyDataErrorInfo {
        private SomeModel rawData = data;
        private string someValue = data.SomeValue.ToString();
        public string SomeValue { get => someValue; set 
        {
            if (SetProperty(ref someValue, value)) 
            {
                // exctractValueFromString adds "nice" validation error 
                // if value cannot be converted.
                var convertedValue = extractValueFromString(value);
                if (convertedValue != null) 
                {
                    // Handle validation here
                    ...
                    // Update underlying data
                    SetProperty(ref rawData.SomeValue, convertedValue, nameof(SomeValue));
                }
            }
        }
        // Implement INotifyDataErrorInfo
        ...
    }
    

    The extractValueFromString method accepts string value that we need to convert and tries to parse it into needed type. And if it fails it returns null and adds a validation error for this property.

    Now instead of binding DataGrid to actual data in SomeModel I bind it to that "wrapper". This way whenever value in DataGrid changes it is always accepted regardless of it being convertible to target type (the one in SomeModel) and I handle that conversion (and it's errors) myself.

    It looks quite bad and adds a lot of extra code with potentially some other problems but it seems to work for me and all the extra problems hopefully are MY problems now and not framework's (which means I don't have to wait for framework devs to solve them for me)