为什么我的 MenuFlyoutItem 文本绑定不起作用?

Why is my MenuFlyoutItem text binding not working?

ItemsSource 列表的绑定正在运行。我知道是因为该列表包含四个项目,并且在我测试时,我的弹出菜单也有四个项目。问题是每个 MenuFlyoutItem 都是空白的。在下面的代码中,SourceForCompaniesList 是公司类型的 ObservableCollection。 CompanyName 是公司的字符串 属性。我已在组合框中成功绑定到此列表,但无法在弹出菜单中使用它。有人可以告诉我我做错了什么吗?

<FlyoutBase.AttachedFlyout>
    <Flyout helpers:BindableFlyout.ItemsSource="{Binding ElementName=thePage, Path=DataContext.SourceForCompaniesList}" x:Name="theFlyout">
        <helpers:BindableFlyout.ItemTemplate>
            <DataTemplate>
                <MenuFlyoutItem Text="{Binding ElementName=theFlyout,Path=DataContext.CompanyName}" />
            </DataTemplate>                                                             
        </helpers:BindableFlyout.ItemTemplate>
    </Flyout>                                                       
</FlyoutBase.AttachedFlyout>

打开菜单截图:

项目 Text 绑定可以用更简单的方式重写,应该可以正常工作:

<FlyoutBase.AttachedFlyout>
    <Flyout helpers:BindableFlyout.ItemsSource="{Binding ElementName=thePage, Path=DataContext.SourceForCompaniesList}" x:Name="theFlyout">
        <helpers:BindableFlyout.ItemTemplate>
            <DataTemplate>
                <MenuFlyoutItem Text="{Binding CompanyName}" />
            </DataTemplate>                                                             
        </helpers:BindableFlyout.ItemTemplate>
    </Flyout>                                                       
</FlyoutBase.AttachedFlyout>

请注意,我只使用 CompanyName,因为 DataTemplate 的上下文实际上是来自绑定项目源的单个 Company,因此您绑定的是 相对于公司项目本身

注意,要获得更好的性能,您可以使用 x:DataTypex:Bind:

<FlyoutBase.AttachedFlyout>
    <Flyout helpers:BindableFlyout.ItemsSource="{Binding ElementName=thePage, Path=DataContext.SourceForCompaniesList}" x:Name="theFlyout">
        <helpers:BindableFlyout.ItemTemplate>
            <DataTemplate x:DataType="YourXmlNamespace:Company">
                <MenuFlyoutItem Text="{x:Bind CompanyName}" />
            </DataTemplate>                                                             
        </helpers:BindableFlyout.ItemTemplate>
    </Flyout>                                                       
</FlyoutBase.AttachedFlyout>

您需要在根元素(很可能是 Page)中将 YourXmlNamespace 声明为 xmlns 命名空间。此版本性能更高,因为它使用编译绑定 (x:Bind) 而不是基于反射的 Binding.