【发布时间】:2015-05-23 00:24:13
【问题描述】:
我有一个 ComboBox(在 ListView 内),它曾经被绑定到一组字符串。但是,我正在改用自定义类。
现在 ComboBox 已绑定到类型为 Area 的 ObservableCollection。为了显示,我使用 DisplayMemberPath 显示 Name 属性。这很好用,但该框不再加载当前选定的值。
<ListView x:Name="TestListView" ItemsSource="{Binding TestViewList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListView.View>
<GridView>
<GridViewColumn Header="Area">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.AreaList, ElementName=BVTWindow}" DisplayMemberPath="Name" SelectedItem="{Binding Path=Area, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
public ObservableCollection<ViewTest> TestViewList { get; private set; }
public ObservableCollection<Area> AreaList { get; private set; }
public class ViewTest : BindableBase
{
public string Description { get; set; }
public Area Area { get; set; }
}
public partial class Area
{
public long ID { get; set; }
public string Name { get; set; }
}
“Area”与 Collection 是同一个类,是 ListView 的 ItemsSource 绑定到的类的属性。我这样做对吗?非常感谢任何帮助。
更新:
我有一个理论,可能使用“名称”属性(它是一个字符串)在框中显示,使 SelectedItem 属性查找字符串而不是区域类型的东西。我更改了 TestViewList 的类以使用字符串来跟踪 Area,但这根本没有改变程序的行为。
更新 2:
在上面,我从视图模型中添加了与相关 ComboBox 和 ListView 相关的相关行。
更新 3:
我已将我的 Area 属性从内联更改为扩展,包括处理提升的 SetProperty。它现在适用于在运行时添加到 ItemSource 的新项目,但对于在程序启动时加载的项目仍然是空白选择。
public class ViewTest : BindableBase
{
public string Description { get; set; }
public Area Area
{
get
{
return this.area;
}
set
{
this.SetProperty(ref this.area, value);
}
}
}
更新 4:
事实证明 Paul Gibson 的回答是正确的。我现有条目未正确加载的原因与我从数据库加载项目的方式中的逻辑错误有关,而不是 xaml 绑定的问题。现在一切正常(至少就那些组合框而言)。
【问题讨论】:
-
你能给我们看看 ViewModel 代码吗?我猜这 Area 是一种类型,所以在你的视图模型中你应该有一个 Area 类型的属性,称为 CurrentSelection (例如)。那么您的绑定将是: SelectedItem="{Binding DataContext.CurrentSelection . . . }".
-
@PaulGibson:谢谢,保罗。 ViewTest.Area 是我绑定到 SelectedItem 的属性。 TestViewList 中的每个条目在 ListView 中都有自己的 ComboBox 和自己的 SelectedItem。
标签: wpf data-binding selecteditem