Hello.
I'm having problems binding text to a label inside a custom control.
I have made the following control:
<?xml version="1.0" encoding="UTF-8"?> <ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Frida3.Components.TestView"> <ContentView.Content> <StackLayout> <Label Text="{Binding Text}" /> </StackLayout> </ContentView.Content> </ContentView>
With the following code-behind:
[XamlCompilation(XamlCompilationOptions.Compile)] public partial class TestView : ContentView { public TestView () { InitializeComponent (); BindingContext = this; } public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(TestView), default(string)); public string Text { get => (string) GetValue(TextProperty); set => SetValue(TextProperty, value); } }
When using the control and a binding to set the Text property, nothing is shown. Below is some sample code of showing the results:
<!-- Shows that the LoginText binding contains value --> <Label Text="{Binding LoginText}" BackgroundColor="BurlyWood"/> <!-- Nothing shown with same binding --> <components:TestView Text="{Binding LoginText}" BackgroundColor="Aqua" /> <!-- Works without binding --> <components:TestView Text="This is showing" BackgroundColor="Yellow" />
And here is the result of that:
Just a guess but try
<?xml version="1.0" encoding="UTF-8"?> <ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Frida3.Components.TestView" x:Name="MyPage"> <ContentView.Content> <StackLayout> <Label Text="{Binding Path=Text, Source={x:Reference Name=MyPage}}" /> </StackLayout> </ContentView.Content> </ContentView>
hard to say without seeing what your binding context is etc. You really need to post a repo.
Answers
Just a guess but try
hard to say without seeing what your binding context is etc. You really need to post a repo.
Thank you, that worked. Is there no "shorthand" to avoid adding Source to every single element in my that I want to databind to a property?
@Inrego
Well the default behaviour is to bind to the bindingcontext property of the page, not the page itself, you can actually specify
BindingContext.Command
etc in a data template etc within a listview which is really useful as it takes you to whatever Viewmodel is bound and whatever property if you like stuff to be loosely coupled. If your writing a reusable control like your doing then this approach works fine where the parent is the binding context.I won't even pretend to understand why it wasn't working before. I'm just happy it's working now!