gpt4 book ai didi

c# - 绑定(bind)到 ItemsSource 中的属性

转载 作者:行者123 更新时间:2023-11-30 22:33:48 25 4
gpt4 key购买 nike

我有如下类:

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

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

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

我的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 在显示时返回名称值(因为我已将 displaymemberpath 设置为名称)而不是以字符串格式返回整个对象。

我怎样才能做到这一点?

最佳答案

使用以下内容:

<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

关于c# - 绑定(bind)到 ItemsSource 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com