我有一个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绑定到的类的属性。我这样做对吗?非常感谢您的帮助。
更新:
我有一个理论,也许使用"Name"属性(这是一个字符串)在框中显示会使SelectedItem属性看起来像一个字符串,而不是Area类型的东西。我更改了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:
事实证明保罗·吉布森的回答是正确的。我的现有条目没有正确加载的原因与我从数据库加载项目的方式中的逻辑错误有关,而不是xaml绑定的问题。现在一切正常(至少对于那些组合框)。
根据你所说的,我认为我的评论就是答案。这是单个组合框的情况。在您的情况下,网格的每一行都需要一个绑定,因此您可能必须通过编程将绑定添加到索引列表的成员。
在您的视图模型中,如果您也有(单个案例):
private Area _curSelArea;
public Area curSelArea
{
get { return _curSelArea; }
set
{
_curSelArea = value;
RaisePropertyChanged("curSelArea");
}
}
然后你可以用绑定到属性
SelectedItem="{Binding DataContext.curSelArea . . . }"
如果最初已知curSelArea的初始值,则视图模型可以设置该值。
编辑:在实际操作之后,我发现有人扩展了DataGridComboBoxColumn以便于更好地绑定。如果您正在尝试执行此操作,请查看此链接:http://joemorrison.org/blog/2009/02/17/excedrin-headache-35401281-using-combo-boxes-with-the-wpf-datagrid/