WPF DataGrid, application crash when adding a row

前端 未结 6 1673
青春惊慌失措
青春惊慌失措 2021-02-08 02:29

I have a wpf datagrid bound to a TrackableCollection. In some rare occations, and for only a few selected users, the application will crash when the user adds a new record by en

6条回答
  •  情深已故
    2021-02-08 02:56

    I know this is pretty old, but there is a good solution to this problem that I came across. You can define a custom converter using the IValueConverter interface:

    public class SelectedItemConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value ?? DependencyProperty.UnsetValue;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value == null || value.GetType().Name == "NamedObject") ? null : value;
        }
    }
    

    This checks if the value is null and if it is, returns DependecyProperty.UnsetValue. As described in the documentation (look at the method descriptions):

    A return value of DependencyProperty.UnsetValue indicates that the converter produced no value and that the binding uses the FallbackValue, if available, or the default value instead.

    Returning this rather than null should fix the issue.

提交回复
热议问题