WPF:SelectedItem绑定不显示DisplayMemberPath

时间:2015-03-19 18:20:56

标签: wpf data-binding selecteditem

我有一个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:

事实证明保罗吉布森的回答是正确的。我现有条目未正确加载的原因与我从数据库加载项目的方式中的逻辑错误有关,而不是xaml绑定的问题。现在一切都有效(至少对于那些ComboBoxes而言)。

1 个答案:

答案 0 :(得分:1)

根据您所说的内容,我认为我的评论就是答案。这是单个组合框的情况。在您的情况下,您需要为网格的每一行添加一个,因此您可能必须通过索引以编程方式将绑定添加到列表成员。

在您的视图模型中,如果您还有(单个案例):

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/

相关问题