views:

45

answers:

2

Elements and FirstAttribute bind as I'd expect (if I didn't know it's a method), but Attributes does not, despite being a member of XElement, just like the others. I know about IValueConverter, and I'm using that to get the binding I want on attributes, but I'm curious as to why it works on Elements.

<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();
        }
    }
}
A: 

Are you sure Elements works? Because as far as I know, you can't bind directly to a method. Elements and Attributes are both methods, to get around this see this question.

Bryce Kahle
That's what I thought, too, but binding directly to Elements does indeed work.I did resort to an IValueConverter for attributes.
Wayne
A: 

Got the answer on MSDN:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/4be39d21-c9d8-4781-9337-2cb1215ec3d1/

Basically, the XAML team added PropertyDescriptors to XLinq specifically for binding, but must have forgotten about Attributes...

Wayne