无法使用 Xamarin Prism 7.1 在部分视图中设置绑定到 BindableProperties

Unable to set bindings to BindableProperties in Partial Views using Xamarin Prism 7.1

我在 Xamarin 中使用 Prism 7.1 的部分视图功能,其中 ContentView 可以拥有自己的 ViewModel。与视图模型的绑定工作正常。但是,我还想设置一个 BindableProperty。例如,我想在 ContentView 上设置一个标题 属性。如果 ContentView 没有自己的 ViewModel,则 Binding 可以正常工作。如果它确实有自己的 ViewModel,则绑定永远不会发生。

MainPage.xaml
<controls:CustomContentView  Title="My Custom View Title"
    mvvm:ViewModelLocator.AutowirePartialView="{x:Reference self}"/>

CustomContentView.cs:
public static readonly BindableProperty TitleProperty = 
        BindableProperty.Create(
        nameof(Title),
        typeof(string),
        typeof(CustomContentView));

public string Title
{
    get => (string)GetValue(TitleProperty);
    set => SetValue(TitleProperty, value);
}

CustomContentView.xaml:
    <ContentView.Content>
      <StackLayout>
          <Label Text="{Title}" />
    </StackLayout>
</ContentView.Content>

如果我在 Title 的 set 方法上设置断点,它永远不会被命中并且 Label 控件中的 Title 永远不会被绑定。

通过使用局部视图,您的绑定上下文是视图的 ViewModel 而不是视图本身...

通过在 CustomContentView 中设置 Label 的文本,例如:

<StackLayout>
  <Label Text="{Binding Title}" />
</StackLayout>

这将绑定到类似的东西:

public class CustomContentViewModel : BindableBase
{
    private string _title;
    public string Title
    {
        get => _title;
        set => SetProperty(ref _title, value);
    }
}

由于您期望从后面的代码中提取绑定,因此 XAML 需要类似于:

<ContentView x:Class="AwesomeApp.Views.CustomContentView"
             x:Name="self">
  <StackLayout>
    <Label Text="{Binding Title,Source={x:Reference self}}" />
  </StackLayout>
</ContentView>