Wpf 为什么在这种情况下其中一条路径不绑定?
元素和FirstAttribute按照我的预期绑定(如果我不知道这是一个方法的话),但是属性没有绑定,尽管它是XElement的成员,就像其他属性一样。我知道IValueConverter,我用它来获得我想要的属性绑定,但我很好奇为什么它能在元素上工作Wpf 为什么在这种情况下其中一条路径不绑定?,wpf,data-binding,linq-to-xml,Wpf,Data Binding,Linq To Xml,元素和FirstAttribute按照我的预期绑定(如果我不知道这是一个方法的话),但是属性没有绑定,尽管它是XElement的成员,就像其他属性一样。我知道IValueConverter,我用它来获得我想要的属性绑定,但我很好奇为什么它能在元素上工作 <Window x:Class="WpfApplication6.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmln
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBlock Text="{Binding Path=FirstAttribute}" />
<ListBox ItemsSource="{Binding Path=Elements}" />
<ListBox ItemsSource="{Binding Path=Attributes}" />
</StackPanel>
</Window>
using System.Linq;
using System.Windows;
using System.Xml.Linq;
namespace WpfApplication6 {
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
XDocument doc = new XDocument(
new XElement("Parent",
new XAttribute("attr1", "val"),
new XAttribute("attr2", "val"),
new XElement("Child1"),
new XElement("Child2")
)
);
MessageBox.Show("Elements: " + doc.Elements().First().Elements().Count());
MessageBox.Show("Attributes: " + doc.Elements().First().Attributes().Count());
DataContext = doc.Elements().First();
}
}
}
使用System.Linq;
使用System.Windows;
使用System.Xml.Linq;
命名空间WpfApplication6{
///
///Window1.xaml的交互逻辑
///
公共部分类Window1:Window{
公共窗口1(){
初始化组件();
XDocument doc=新XDocument(
新XElement(“父项”,
新XAttribute(“attr1”、“val”),
新XAttribute(“attr2”、“val”),
新XElement(“Child1”),
新XElement(“Child2”)
)
);
Show(“元素:+doc.Elements().First().Elements().Count());
Show(“属性:+doc.Elements().First().Attributes().Count());
DataContext=doc.Elements().First();
}
}
}
您确定元素有效吗?因为据我所知,您不能直接绑定到方法。元素和属性都是解决此问题的方法,请参见。在MSDN上获得了答案:
基本上,XAML团队向XLinq添加了专门用于绑定的PropertyDescriptor,但肯定忘记了属性…我也是这么想的,但是直接绑定到元素确实有效。我确实求助于IValueConverter获取属性。