【问题标题】:Binding to property within the ItemsSource绑定到 ItemsSource 中的属性
【发布时间】:2011-11-14 04:26:29
【问题描述】:

我有如下课程:

class test
{
  public string Name;
  public string Location;
}

通过使用实体框架的查询结果,我得到了一组测试对象,我直接将其设置到我的列表框。但是使用 DisplayMemberPath Iam 只是显示 Name 值。所以现在列表框包含整个测试对象集合,但只显示名称值。

当我尝试绑定到列表框的选定项时,我将整个测试对象作为字符串获取,但我只需要选定项结果中的名称值。

我的 XAML 如下:

<ListBox x:Name="lbSubSelector" Height="200" DisplayMemberPath="Name" SelectedItem="{Binding Name, Mode=TwoWay}" />

我填充列表的代码如下:

 LoadOperation<test> subLoadOp = context.Load(context.GetTestQuery());
 lbSubSelector.ItemsSource = subLoadOp.Entities;
 lbSubDistrictSelector.DataContext = SkillModel.Instance;

selectedItem 设置为的 DataContext 具有测试对象的整个字符串表示形式的值,但我希望 selecteditem 在显示时仅返回 Name 值(因为我已将 displaymemberpath 设置为 Name)而不是以字符串格式返回整个对象。

我怎样才能做到这一点?

【问题讨论】:

  • 您需要了解 listbox 的 SelectedValue 和 SelectedValuePath 属性。
  • @stukselbax,您需要发布此评论作为答案。

标签: c# wpf silverlight xaml


【解决方案1】:

使用以下:

<ListBox x:Name="lbSubSelector" Height="200" DisplayMemberPath="Name" SelectedValuePath="@Name" />

然后您可以使用 lbSubSelector.SelectedValue 来获取所选项目的 Name 属性。

见: http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectedvaluepath.aspx

【讨论】:

    【解决方案2】:

    请使用 Listbox 上的 IsSynchronizedWithCurrentItem 属性,并将 SelectedItem 绑定更改为 xaml 代码中的 /Name,如下所示:

    <ListBox x:Name="lbSubSelector" Height="200" DisplayMemberPath="Name" SelectedItem="{Binding /Name, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True"/>
    

    【讨论】:

      【解决方案3】:

      我建议您将 ListView 与 GridColumns 一起使用,而不是使用 ListBox。以下是 sn-p,您可能需要相应地对其进行修改。但这肯定会按照您希望的方式工作:-

      <ListView Name="ListView1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" MouseDoubleClick="transactionListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" >
                          <ListView.View>
                              <GridView ColumnHeaderContainerStyle="{StaticResource gridViewHeaderColumnStyle}">
                                  <GridView.Columns>
                                      <GridViewColumn Width="70" Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
                                      <GridViewColumn Width="270" Header="Seller" DisplayMemberBinding="{Binding Path=Location}" />
                                  </GridView.Columns>
                              </GridView>
                          </ListView.View>
                      </ListView>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 2012-01-08
        • 2011-05-22
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多