【问题标题】:Why is my MenuFlyoutItem text binding not working?为什么我的 MenuFlyoutItem 文本绑定不起作用?
【发布时间】:2019-09-09 19:10:34
【问题描述】:

ItemsSource 列表的绑定正在工作。我可以说出来,因为列表包含四个项目,当我测试时,我的弹出菜单也有四个项目。问题是每个MenuFlyoutItem 都是空白的。在下面的代码中,SourceForCompaniesList 是 Company 类型的 ObservableCollection。 CompanyName 是 Company 的字符串属性。我已成功绑定到组合框中的此列表,但无法使其在弹出菜单中工作。谁能告诉我我做错了什么?

<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>

打开菜单截图:

【问题讨论】:

  • 你确定Binding Path 是正确的吗?你能说明你正在使用什么上下文以及你是如何绑定它的吗?
  • 我确信顶层弹出绑定是正确的。但是 MenuFlyoutItem 绑定有问题。 CompanyName 绝对是 Company 的属性,它是 SourceForCompanies 列表中包含的项目类型。但是,我的路径一定有问题……我猜它没有与 SourceForCompanies 列表绑定,但我不知道为什么。
  • 我正在尝试使用包含数据模板的浮出控件的上下文。这显然行不通。 SourceForCompaniesList 是 viewmodel 中的一个 Observable 集合。谢谢。

标签: c# xaml uwp mvvm-light


【解决方案1】:

项目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,因此您将 relative 绑定到公司项目本身.

注意,为了获得更好的性能,你可以使用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

【讨论】:

  • 知道了!谢谢!我试过 {Binding Company},但没有试过 {Binding CompanyName}。阅读您的解释后,这完全有道理。
  • 很高兴它有帮助!
猜你喜欢
  • 2011-01-16
  • 2011-09-29
  • 2020-05-21
  • 1970-01-01
  • 2016-10-06
  • 2021-09-23
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多