Can a Bindable property in a ContentView be of type Func<bool>? That is, something like this:
public partial class MyControl : ContentView
{
public static readonly BindableProperty DoSomethingProperty = BindableProperty.Create(
nameof(DoSomething),
typeof(Func<bool>),
typeof(MyControl);
public Func<bool> DoSomething
{
get => (Func<bool>)GetValue(DoSomethingProperty);
set => SetValue(DoSomethingProperty, value);
}
}
Then you could use it in a page like such:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:MauiPlayground.Controls"
x:DataType="vm:MainPageViewModel"
x:Class="MauiPlayground.MainPage">
<ContentPage.Content>
<VerticalStackLayout>
<controls:MyControl DoSomething="{Binding ViewModelDoSomething}" />
</VerticalStackLayout>
</ContentPage.Content>
</ContentPage>
And the MainPageViewModel would contain this method:
public bool ViewModelSoSomething()
{
return true;
}
(This isn't actual code, just wondering if this can be done in theory. If, for example, you want to pass a callback function or method to the ContentView)
I tried doing something like this and the compiler didn't complain, but the value of the DoSomething property was never set. Maybe there's another way of doing this?
You can achieve this by adding
BindablePropertyof typeICommandto yourContentViewand you can also pass data to the command by addingBindablePropertyof typeobject.I achieved this function on my side,And I also added a common property
YourNameto my ContentView.Please refer to the following code:
MyControl.xaml
MyControl.xaml.cs
Usage example:
TestViewModel.cs