OnApplyTemplate不能捕获父对象的BindingContext吗?

时间:2019-12-13 21:42:19

标签: xamarin.forms data-binding

在一个测试项目中,我正在尝试通过模板绑定获得父控件的BindingContext

MainPage中,我有两个模板temp1temp2

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:MyXam.ViewModels"
             xmlns:views="clr-namespace:MyXam.Views"
             x:Class="MyXam.Views.MainPage"
             x:DataType="vm:MainViewModel">
    <ContentPage.Resources>
        <ResourceDictionary>
            <ControlTemplate x:Key="temp1">
                <views:View1/>
            </ControlTemplate>
            <ControlTemplate x:Key="temp2">
                <views:View2/>
            </ControlTemplate>

        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout x:Name="stk">
        <Button Text="Switch view" Command="{Binding SwitchViewCommand}"/>
        <ContentView x:Name="cv" ControlTemplate="{StaticResource temp2}" VerticalOptions="Start" HorizontalOptions="Center">
            <ContentView.Triggers>
                <DataTrigger TargetType="ContentView" Binding="{Binding IsView1}" Value="False">
                    <Setter Property="ControlTemplate" Value="{StaticResource temp2}"/>
                </DataTrigger>
                <DataTrigger TargetType="ContentView" Binding="{Binding IsView1, Mode=TwoWay}" Value="True">
                    <Setter Property="ControlTemplate" Value="{StaticResource temp1}"/>
                </DataTrigger>
            </ContentView.Triggers>
        </ContentView>
    </StackLayout>
</ContentPage>

我想在ctor中获取BindingContextMainPage的{​​{1}}:

View2

但是当我尝试在SetBinding(BindingContextProperty, new Binding("Parent.BindingContext", source: RelativeBindingSource.TemplatedParent)); 中获取其vzlue时,它为null:

OnApplyTemplate

但是在xaml中解析绑定:

 protected override void OnApplyTemplate()
 {
     base.OnApplyTemplate();
     vm = this.GetValue(BindingContextProperty);
 }

1 个答案:

答案 0 :(得分:0)

我看不到其他代码的详细信息,但是您可以参考以下代码。

BindableProperty中为此标签定义一个xaml.cs,并使用Name属性,例如x:Name="TestControlView"并这样绑定

 <Label Text="{Binding Source={x:Reference TestControlView}, Path=TestText}" />

您可以查看完整的演示here。 主要代码如下:

TestControl.xaml.cs(TestControl是ContentView)

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestControl : ContentView
{

    public static readonly BindableProperty TestTextProperty = BindableProperty.Create(nameof(TestText), typeof(string), typeof(TestControl));
    public string TestText
    {
        get { return (string)GetValue(TestTextProperty); }
        set { SetValue(TestTextProperty, value); }
    }

    public TestControl()
    {
        InitializeComponent();
    }        
}

TestControl.xaml

                        

MainPage.xaml

 <ListView  x:Name="lstView" HorizontalOptions="Fill" HasUnevenRows="True"  RefreshAllowed="true" IsPullToRefreshEnabled="true">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame CornerRadius="10" BackgroundColor="White" Margin="0,5,0,5">
                              <StackLayout Orientation="Horizontal" HorizontalOptions="Center">
                                            <controls:TestControl TestText="{Binding Title}"  VerticalOptions="Center"/>
                                            <Label Text="{Binding Type}" FontSize="Medium" TextColor="#F0BB7F" FontAttributes="Bold" VerticalOptions="Center"/>
                              </StackLayout>
                        </Frame>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

MainPage.xaml.cs

 public partial class MainPage : ContentPage
 {
    public ObservableCollection<TestModel> veggies { get; set; }

    public MainPage()
    {
        InitializeComponent();

        veggies = new ObservableCollection<TestModel>();

        veggies.Add(new TestModel { Title = "Tomato", Type = "Fruit" });
        veggies.Add(new TestModel { Title = "Zucchini", Type = "Vegetable" });
        veggies.Add(new TestModel { Title = "Tomato" , Type = "Vegetable" });
        veggies.Add(new TestModel { Title = "Romaine", Type = "Fruit" });
        veggies.Add(new TestModel { Title = "Zucchini", Type = "Vegetable" });

        lstView.ItemsSource = veggies;

        BindingContext = this;
    }
}