将ObservableCollection<XmlNode>绑定到WPF中的组合框

3

我将尝试将一个ComboBox绑定到一个ObservableCollection,但是当表单被显示时,ComboBox是空的。使用字符串类型的ObservableCollection相同的代码完美运行。我认为我的XPath可能是错误的。欢迎任何建议:

XAML:

<ComboBox ItemsSource="{Binding ItemParameters, XPath=InnerXml/name,Mode=TwoWay}" SelectedIndex="0" Margin="2" VerticalAlignment="Top" HorizontalContentAlignment="Stretch" Grid.Row="1" Grid.Column="1" Height="24"  />

ObservableCollection XmlNode :

public ObservableCollection<XmlNode> _itemParameters = new ObservableCollection<XmlNode>();
public ObservableCollection<XmlNode> ItemParameters
{
    get { return _itemParameters; }
    set { _itemParameters = value; }
}

组合框应该显示集合中每个XmlNode的name属性: enter image description here 更新: 我已经尝试使用DisplayMemberPath两种不同的方式,但组合框仍然没有数据:
DisplayMemberPath="{Binding XPath=name}" ItemsSource="{Binding ItemParameters}"
DisplayMemberPath="{Binding XPath=InnerXml/name}" ItemsSource="{Binding ItemParameters}"

解决方案:

这个方法很有效,希望能对其他人也有用:

<ComboBox DisplayMemberPath="@name" ItemsSource="{Binding ItemParameters}"

1
由于您对属性“name”感兴趣,而不是元素名称,请在xpath中使用“@name”,如http://www.w3schools.com/xpath/xpath_syntax.asp所述。 - Patrick
1个回答

3
首先,您同时设置了PathXPath,这些是冲突的属性。其次,您绑定了ItemsSource,这与您想要在项内显示的内容无关。请使用DisplayMemberPathItemTemplateItemsSource应该只绑定到ItemParameters

谢谢您的回答,我相信我没有同时设置Path和Xpath...如果您查看XAML,您会发现只有XPath被设置了。或者我漏掉了什么吗? - Denys Wessels
1
@Deni:ItemParameters 设置为 Path 属性,这是隐式的。 - Patrick
@Deni:通常在标记扩展中,未命名的参数会传递给基础类的构造函数,Binding有一个接受字符串的构造函数,该字符串用作Binding.Path - H.B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接