TwoWay bind WPF ComboBox to XDocument

I have a ComboBox bound to a XDocument and it does not write back value changes:

teams.xml

<?xml version="1.0" encoding="utf-8" ?>
<teams>
  <team>
    <name>Team A</name>
    <leader>C</leader>
    <members>
      <member>A</member>
      <member>B</member>
      <member>C</member>
    </members>
  </team>
  <team>
    <name>Team B</name>
    <leader>B</leader>
    <members>
      <member>B</member>
      <member>D</member>
      <member>E</member>
    </members>
  </team>
</teams>

MainWindow.xaml

<Window x:Class="Teamleader.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <DataGrid Name="grid" ItemsSource="{Binding}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Team" Binding="{Binding Path=Element[name].Value}"></DataGridTextColumn>
                <DataGridTemplateColumn Header="Leader">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox ItemsSource="{Binding Path=Element[members].Descendants, PresentationTraceSources.TraceLevel=High}"
                                      SelectedValue="{Binding Path=Element[leader].Value, PresentationTraceSources.TraceLevel=High, Mode=TwoWay}"
                                      SelectedValuePath="Value"
                                      DisplayMemberPath="Value"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Leader Text (only for testing)" Binding="{Binding Path=Element[leader].Value, Mode=TwoWay}"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Content="Save" HorizontalAlignment="Right" VerticalAlignment="Bottom" Click="SaveButton_Click" />
    </Grid>
</Window>

MainWindow.xaml.cs

namespace Teamleader
{
    public partial class MainWindow : Window
    {
        private XDocument doc;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            doc = XDocument.Load("teams.xml");

            var teams = from team in doc.Root.Descendants("team") select team;

            grid.DataContext = teams.ToList();
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            doc.Save("teams-output.xml");
        }
    }
}

When I change the SelectedItem of the ComboBox by clicking on it, my OutputWindow shows me the following four lines:

System.Windows.Data Information: 41 : BindingExpression path error: 'Value' property not found for 'object' because data item is null. This could happen because the data provider has not produced any data yet. BindingExpression:Path=Value; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=Value; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=Value; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Value; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

When I change the SelectedItem of the ComboBox, the corresponding TextBox does not change its value. When I change the value in the TextBox, the ComboBox adapts at once (given that the value is in the list). Also, values changed by using the TextBox get written back into the XDocument. Changing values by using the ComboBox has no effect.

My target framework is .NET Framework 4.5, my system is running Windows7 x64.

I have found ComboBox twoway binding with XElement , but the mentioned hotfix is for .NET 4.0 - I guess it should be fixed by now. Installing the hotfix does not work on my system.

I also found WPF ComboBox SelectedValue not updating from binding source . Using SelectedItem instead of SelectedValue gives me a System.InvalidOperationException telling me that a TwoWay or OneWayToSource binding cannot work on the read-only property 'Item' (type MS.Internal.Xml.Linq.ComponentModel.XDeferredSingleton).

Can anyone point my error out or tell me if that error from .NET Framework 3.5 still exists?

Answers


UpdateSourceTrigger=PropertyChanged does only work with .NET < 4.5 and the hotfix from KB2328886 or .NET 4.5 and above. To get it fixed with old frameworks without the hotfix, try this to manually trigger the required events:

<ComboBox ItemsSource="{Binding Path=Element[ActionOptions].Descendants}"
            SelectedValue="{Binding Path=Element[CurrentActionOption].Value, Mode=TwoWay}"
            SelectedValuePath="Value"
            SelectionChanged="SelectedIndexChanged"
            DisplayMemberPath="Value"
            Visibility="{Binding Path=Element[ActionOptionsVisibility].Value}"/>
private void SelectedIndexChanged(object sender, RoutedEventArgs e)
{
    var bindingExpression = ((ComboBox)sender).GetBindingExpression(ComboBox.SelectedValueProperty);
    bindingExpression.UpdateSource();
}

Need Your Help

Broken History in IOS7

jquery jquery-mobile backbone.js ios7 backbone-routing

I'm building SPA(single page app) using Backbone(1.1.2) and Jquery Mobile(1.4.2), and I'm experiencing strange things when browsing web site with IPhone( running IOS7,lower versions work just fine...

How to i use TFS with Visual studio 2010 to simulate multiple users?

c# winforms visual-studio-2010 tfs codeplex

i'm using VS2010 with free version of the TFS provided with codeplex. but i'm only working on one PC. i tried to simulate two users by opening two VS and login to TFS from two user names. then when...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.