Search code examples
c#.netdata-bindingmaui.net-maui

Data binding to BindableProperty results in error "mismatching type between value and property"


I'm trying to get the following to work within my .NET MAUI project.

I have a view SettingView, which has a BindableProperty of type string.

    internal class SettingView : ContentView
    {
        public static readonly BindableProperty BoundObjectPropery = BindableProperty.Create(
                nameof(BoundObject),
                typeof(string),
                typeof(SettingView),
                defaultValue: "",
                propertyChanging: BoundObjectChanged,
                defaultBindingMode: BindingMode.OneWay);

        public string BoundObject
        {
            get => (string)GetValue(BoundObjectPropery);
            set => SetValue(BoundObjectPropery, value);
        }
    }

I can call this from XAML as follows:

    <local:SettingView BoundObject="LiteralString" />

The provided String is passed and can be used from the SettingView.

But when I try to pass a property from the view model with a DataBinding, VS refuses to build and I get an error

I have the following property declared in my view model

public string TestString => "Lorum ipsum";

XFC0009 No property, BindableProperty, or event found for "BoundObject", or mismatching type between value and property

<local:SettingView BoundObject="{Binding TestString}" />

But when I use 'primitive' views, like a Label, it works just fine..

<Label Text="{Binding TestString}"/>

If I use type Object instead of type string, it does build and run, and I receive an object of type "Binding". But it seems I can't do anything meaningful with this object.

Intellisense does complain that there is 'No DataContext found for Binding 'TestString'", but that shouldn't be an issue since it doesn't know anything about the DataContext at compiletime when using MVVM.

Can anyone see what I'm doing wrong?


Solution

  • Froms the official docs bindable properties: Create a property

    The naming convention for bindable properties is that the bindable property identifier must match the property name specified in the Create method, with "Property" appended to it.

    You made a typo BoundObjectPropery instead of BoundObjectProperty (same for BoundStringProperty) that why you had the compilation error:

    internal class SettingView : ContentView
    {
        public static readonly BindableProperty BoundObjectProperty = BindableProperty.Create(
                nameof(BoundObject),
                typeof(string),
                typeof(SettingView),
                defaultValue: "",
                propertyChanging: BoundObjectChanged,
                defaultBindingMode: BindingMode.OneWay);
    
        public string BoundObject
        {
            get => (string)GetValue(BoundObjectProperty);
            set => SetValue(BoundObjectProperty, value);
        }
    }