Skip to content

ComboBox binding throws exception: Unable to cast object of type 'Avalonia.Controls.Utils.BindingEvaluator`1[System.Object]' toΒ #18822

Closed
@voytas

Description

@voytas

Describe the bug

This started happening after updating to 11.3.0. Previous versions seem not to have this issue. Therefore not sure if something has changed or it indicates some internal binding issue.

Basically when binding ComboBox using SelectedValueBinding and SelectedValue, and running in debug mode, the following exception is thrown:

System.InvalidCastException: Unable to cast object of type 'Avalonia.Controls.Utils.BindingEvaluator`1[System.Object]' to type 'ComboBoxTest.NameValueTest'.
at CompiledAvaloniaXaml.XamlIlHelpers.ComboBoxTest.NameValueTest,ComboBoxTest.Value!Getter(Object)
at Avalonia.Data.Core.ClrPropertyInfo.Get(Object target)
at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.get_Value()
at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SendCurrentValue()

Alternatively if you enable logging, binding error will be logged if running in non debug mode.

To Reproduce

Create a simple project using below binding and view model. Make sure that you either enable error logging in Avalonia or run in debug mode with breakpoints enabled on exceptions.

<ComboBox
        ItemsSource="{Binding Items}"
        SelectedValue="{Binding SelectedItem}"
        DisplayMemberBinding="{Binding Name}"
        SelectedValueBinding="{Binding Value}"/>
public class NameValueTest
{
    public string Name { get; set; } = string.Empty;
    public int Value { get; set; }
}
public class ViewModel
{
    public ObservableCollection<NameValueTest> Items { get; set; } = [];

    public int SelectedItem { get; set; }

    public ViewModel()
    {
        Items.Add(new NameValueTest() { Name = "Option 1", Value = 1 });
        Items.Add(new NameValueTest() { Name = "Option 2", Value = 2 });
        Items.Add(new NameValueTest() { Name = "Option 3", Value = 3 });
    }
}

Expected behavior

No exception thrown or binding error reported.

Avalonia version

11.3.0

OS

macOS

Additional context

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions