I encounter an issue while I'm creating a Custom control in my Xamarin forms app.
I create a bindable property for the label label called "NameLabel" in this xaml file :
<Grid
x:Class="Kwikwink.Controls.SelectedGatewayFrame"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit">
<StackLayout>
<Frame >
<StackLayout Orientation="Horizontal">
<StackLayout>
...
<Label
x:Name="NameLabel"
FontFamily="InterMed"
TextColor="{StaticResource DetailTextColor}"
VerticalOptions="Center" />
</StackLayout>
...
</StackLayout>
</Frame>
</StackLayout>
</Grid>
with this code in my xaml.cs file
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SelectedGatewayFrame : Grid
{
public static readonly BindableProperty GatewayNameProperty = BindableProperty.Create(nameof(Name),
typeof(string),
typeof(SelectedGatewayFrame),
defaultValue: string.Empty,
propertyChanged: GatewayNamePropertyChanged);
private static void GatewayNamePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (SelectedGatewayFrame)bindable;
control.NameLabel.Text = newValue?.ToString();
}
public string Name
{
get => GetValue(GatewayNameProperty)?.ToString();
set => SetValue(GatewayNameProperty, value);
}
public SelectedGatewayFrame()
{
InitializeComponent();
}
}
And finaly a use it like this in other views:
<controls:SelectedGatewayFrame Name="Test string" />
With the string set here it work perfectly !!
My problem come when I try to bound this property to somthing in a viewmodel (public string tmp { get; set; } = "meph";
for exemple) :
like so :
<controls:SelectedGatewayFrame Name="{Binding tmp}" />
or so :
<controls:SelectedGatewayFrame Name="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:NewAccessTypeViewModel}}, Path=tmp}" />
Then I got this error that show :
No property, BindableProperty, or event found for "Name", or mismatching type between value and property.
I hope this is clear enough, thanks in advance for any help
As a summary, I posted an answer.
For the first problem:
From document Create a property,we know that
So, you need to change
GatewayNameProperty
toNameProperty
or change public stringName
to public stringGatewayName
.For example:
For the second problem:
You need to implement interface INotifyPropertyChanged for your view model.
The
INotifyPropertyChanged
interface is used to notify clients, typically binding clients, that a property value has changed.For exmaple:
And you also need to implement interface
INotifyPropertyChanged
for yourGateway
.