Xamarin Forms binding button Command to parent BindingContext

橙三吉。 提交于 2019-12-01 16:02:47

You can use the Source property to specify a source for the binding that will be used instead of the current BindingContext. Then the text can come from the page's binding context and the command from somewhere else.

Command="{Binding CategorySelectedCommand, Source={x:Static me:SomeStaticClass.YourUserControl}}"

or

Command="{Binding CategorySelectedCommand, Source={DynamicResource yourUserControlKey}}"

or

Command="{Binding CategorySelectedCommand, Source={x:Reference myUserControl}}"

Here's a complete example. A common problem is to not implement INotifyPropertyChanged and set the property after the call to InitializeComponent().

XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="test.MyPage" x:Name="ThePage">
    <Label Text="{Binding TextProp, Source={x:Reference ThePage}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
</ContentPage>

Code behind

public partial class MyPage : ContentPage
{
    public MyPage ()
    {
        this.TextProp = "Some Text";
        InitializeComponent ();
    }

    public string TextProp
    {
        get;
        set;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!