How to get a value from custom control in a broader control via binding in VM

38 Views Asked by At

MAUI.NET

I have a special picker for my own that I want to reuse in many places

<ContentView ...
         x:Class="XYZ.Views.ABCPicker"
         x:DataType="views:ABCPicker">
    <Grid>
        <Picker ItemsSource="{Binding ...}" SelectedItem="{Binding ChoosenDeviceTypeProperty}"/>
    </Grid>
</ContentView>

and its code behind with my AttachedProperty:

public partial class ABCPicker : ContentView
{
    public static readonly BindableProperty ChoosenDeviceTypeProperty = BindableProperty.CreateAttached("ChoosenDeviceType", typeof(string), typeof(ABCPicker), "Detect by connect", BindingMode.TwoWay);
    public static string GetChoosenDeviceType(BindableObject view)
    {
        return (string)view.GetValue(ChoosenDeviceTypeProperty);
    }
    public static void SetChoosenDeviceType(BindableObject view, string value)
    {
        view.SetValue(ChoosenDeviceTypeProperty, value);
    }

    public ABCPicker()
    {
        this.BindingContext = this;
        InitializeComponent();
    }
}

I want to consume it in my broader control ViewModel

public class BroaderControlViewModel : BaseViewModel
{
    ...
    private string myResult;
    public string MyResult
    {
        get { return myResult; }
        set { SetPropertyAndNotify(ref myResult, value); }
    }
    public ICommand MyCommand { private set; get; }
    public BroaderControlViewModel()
    {
        MyCommand = new Command(() =>
        {
            // here I want the to get a choosen value to proceed with it after the user have choosen value in my special picker
        });
    }
}

with a view like below:

<ContentView ...
             x:Class="XYZ.Views.BroaderControlView"
             x:DataType="viewModels:BroaderControlViewModel">
    <VerticalStackLayout ...>
        <views:ABCPicker ChoosenDeviceType="{Binding MyResult, Mode=TwoWay}" />
        <Button Text="Connect" Command="{Binding MyCommand}"/>
    </VerticalStackLayout>
</ContentView>

I tried different binding types, also with x:Reference this and also with normal binding properties - not attached ones.

How it should be matched?

0

There are 0 best solutions below