将ComboBox与LINQ XML绑定

时间:2010-02-26 16:38:44

标签: wpf xml data-binding combobox binding

请原谅我的英语不好,那不是我的母语。

我是WPF和LINQ的初学者(3天以来),也是C#的临时用户。

昨天,我一直在努力解决我的问题,并阅读了几篇文档,但我的代码中的错误仍然存​​在。

我将一个XElement传递给绑定其内容的控件,但我在ComboBox中只有一个

这是XElement的XML:

<racine>
    <element nom="Element 1">
      <rubrique nom="Element 1 - rubrique 1">
        <etat valeur="Hors service">
          <option valeur="En service" />
          <option valeur="Hors service service" />
        </etat>
        <observation>lorem ipsum</observation>
      </rubrique>
      <rubrique nom="Element 1 - rubrique 2">
        <etat>
        </etat>
        <observation>titi toto</observation>
      </rubrique>
    </element>
    <element nom="Element 2">
      <rubrique nom="Element 2 - rubrique 1">
        <etat valeur="foo">
        </etat>
        <observation>youpi</observation>
      </rubrique>
      <rubrique nom="Element 2 - rubrique 2">
        <etat valeur="bar">
          <option valeur="En service" />
        </etat>
        <observation></observation>
      </rubrique>
    </element>
</racine>

以下是我的控件MonControle.xaml.cs背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace MonProjet.Controles
{
    /// <summary>
    /// Logique d'interaction pour MonControle.xaml
    /// </summary>
    public partial class MonControle : UserControl
    {
        XElement xRacine;

        ObservableCollection<XElement> xElementsObservable = new ObservableCollection<XElement>();

        public MonControle()
        {
            InitializeComponent();
            DataContext = xElementsObservable;
        }

        #region Propriété Attribus
        [Category("Configuration"), Browsable(false), Description("Element XML racine")]
        public XElement xRacine
        {
            get
            {
                return xRacine;
            }
            set
            {
                this.xRacine = value;
                MajXElementsObservable();

            }
        }
        #endregion

        private void MajXElementsObservable()
        {
            var requette = from xElements in xRacine.Descendants("element")
                           select (XElement)xElements;
            xElementsObservable.Clear();
            foreach (XElement xElement in requette)
            {
                xElementsObservable.Add(xElement);
            }
        }

    }
}

这是MonControle.xaml的xaml:

<UserControl x:Class="MonProjet.Controles.MonControle"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto">
    <!--
    http://www.youdev.net/post/2008/09/23/WPF-SplitContainer-2.aspx
    http://www.youdev.net/post/2009/03/19/WPF-SplitContainer-Part-2.aspx
    -->
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="25*"/>
            <ColumnDefinition Width="Auto" MinWidth="4"/>
            <ColumnDefinition Width="75*"/>
        </Grid.ColumnDefinitions>
        <DockPanel Grid.Column="0" LastChildFill="True">
            <ListBox Name="lbxElements" ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Attribute[nom].Value" />
        </DockPanel>
        <GridSplitter Grid.Column="1" ResizeBehavior="PreviousAndNext" Width="4" VerticalAlignment="Stretch"/>
        <DockPanel Grid.Column="2" LastChildFill="True" DataContext="{Binding Path=SelectedItem.Elements[rubrique], ElementName=lbxElements, UpdateSourceTrigger=PropertyChanged}">
            <ListBox ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}"
                     IsSynchronizedWithCurrentItem="True">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <GroupBox Header="{Binding Path=Attribute[nom].Value}">
                            <StackPanel Orientation="Horizontal">
                                <!-- http://stackoverflow.com/questions/561166/binding-wpf-combobox-to-a-custom-list -->
                                <ComboBox MinWidth="75" IsEditable="True"
                                          ItemsSource="{Binding Path=Element[etat].Elements[option], UpdateSourceTrigger=PropertyChanged}"
                                          DisplayMemberPath="Attribute[valeur].Value"
                                          SelectedValuePath="Attribute[valeur].Value" 
                                          SelectedValue="{Binding Path=Element[etat].Element[option].Attribute[valeur].Value}"
                                          />
                                <TextBox MinWidth="150" AcceptsReturn="False" AcceptsTab="False" TextWrapping="NoWrap"
                                         Text="{Binding Path=Element[observation].Value, UpdateSourceTrigger=PropertyChanged}" />
                            </StackPanel>
                        </GroupBox>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DockPanel>
    </Grid>
</UserControl>

我的问题是:

  • 当控制加载时,没关系,但是 如果我切换元素在 左侧ListBox,ComboBox的值 变化......尝试很多事情,做很多事 测试,但无法解决它!

  • 不可能输入不是的人 在列表中,但我想要 能够做到这一点。同样,我做了很多 测试,但我无法解决问题

  • 最后但并非最不重要:我想要崛起 ObservableCollection时的事件 更改为写入XML文件, 但不可能抓住一个事件...... 我尝试过类似的东西 xElementsObservable.CollectionChanged + = new NotifyCollectionChangedEventHandler(XElementsObservable_CollectionChanged); 但它不起作用......

先谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

这很难,但我能解决所有问题!

这是解决方案:

在第一时间,ComboBox XAML必须看起来像这样:

<ComboBox MinWidth="75" IsEditable="True"
          IsSynchronizedWithCurrentItem="False"
          ItemsSource="{Binding Path=Element[etat].Elements[option]}"
          DisplayMemberPath="Attribute[valeur].Value"
          Text="{Binding Element[etat].Attribute[valeur].Value, UpdateSourceTrigger=PropertyChanged}"
          />

这个回答问题1和2:当我们关注包含的节点的属性“valeur”的值时,我们可以写出我们想要的东西,即使我们写的值不在集合中,并且, ComboBox文本中节点显示的问题消失了!

对于问题3,我的错误是我专注于可观察的集合!

但是,解决方案很简单,我在XDocument上附加了一个“Changed”事件,其中包含我在这里操作的所有XElements!

所以,我把这段代码放在我软件的主窗口中:

  private void InitPerso()
    {

        xDoc = XDocument.Load(@"C:\fichier.xml");

        xDoc .Changed += new EventHandler<XObjectChangeEventArgs>(XDoc_Changed);

    }

    private void XEdls_Changed(object sender, XObjectChangeEventArgs e)
    {
        xDoc .Save(@"C:\fichier.xml");
    }

Etvoilà!

请原谅我的英语不好,我希望这会有所帮助...