0

我试图让 CarouselView 中的每个视图都具有与父 ContentPage 相同的 BindingContext 对象。我尝试了以下似乎不起作用的方法。MainPage.xaml 是在运行时初始化的页面。它拥有一个 CarouselView,其中有四个 ContentViews 拥有我可以在 MainPage 之间来回滑动的功能“页面”。

MainPage.xaml:

...
<CarouselView Grid.Row="1" Grid.ColumnSpan="4"
              Position="{Binding CarouselPosition}"
              HorizontalScrollBarVisibility="Never">
    <CarouselView.ItemsSource>
        <x:Array Type="{x:Type ContentView}">
            <local:HomeView></local:HomeView>
            <local:NewsView></local:NewsView>
            <local:ChartsView></local:ChartsView>
            <local:SettingsView></local:SettingsView>
        </x:Array>
    </CarouselView.ItemsSource>
    <CarouselView.ItemTemplate>
        <DataTemplate>
            <ContentView Content="{Binding .}" BindingContext="{Binding BindingContext, Source={x:Reference mainPage}}"/>
        </DataTemplate>
    </CarouselView.ItemTemplate>
</CarouselView>
...

基本上,我希望能够将这些 ContentView 中的每一个的 BindingContext 设置为与父级相同。我还读到 ContentViews 有时应该能够继承 BindingContext,但在这种情况下似乎没有发生。

谢谢。

4

1 回答 1

0

这是因为这种控件不会从其父控件继承其 BindingContext,而是将其自己的 BindingContext 设置为绑定到 ItemsSource 的集合的项,这是有意义的。

假设您要显示用户集合。DataTemplate 将是用户的用户界面。您想显示用户的某些属性,而不是您的 ViewModel。

如果要绑定到 ViewModel 中公开的内容而不是 User,则必须将元素的 BindingContext 与 RelativeSource 或通过其 x:Name 定位元素来绑定。

示例:要将 DataTemplate 中的按钮绑定到 ViewModel(而不是 User)中公开的命令,您需要这样做:

<Button
    Text="Try me"
    Command="{Binding
        Path=BindingContext.MyViewModelCommand,
        Source={x:Reference xNameOfParentOutsideDataTemplateOrThePage}" />

为了更容易理解,它的作用是:我想绑定到控件上名为 xNameOfParentOutsideDataTemplateOrThePage (x:Name="xNameOfParentOutsideDataTemplateOrThePage") 的东西。在这个控件上,我想要它的 BindingContext 的一个属性(大多数时候,你的视图模型)。

除了 x:Reference,您还可以使用RelativeSource 绑定

于 2021-06-04T16:05:19.947 回答