使用XElement填充WPF数据网格



我正在尝试使用XElement中的数据填充位于用户控件内部的数据网格。数据网格构建了行,但其中没有显示任何值。我在输出窗口中显示了一个System.Windows.Data Error: 40 : BindingExpression path error: 'Value' property not found on 'object'。我不确定自己做错了什么,我已经看到了几个使用这种方法的例子。我认为这可能与数据网格的位置有关,它在用户控件内,但不确定。

XElement:

<root>
    <option symbol="AAPL131221P00700000" type="P">
        <strikePrice>700</strikePrice>
        <lastPrice>179.53</lastPrice>
        <change>0</change>
        <changeDir />
        <bid>NaN</bid>
        <ask>NaN</ask>
        <vol>30</vol>
        <openInt>60</openInt>
    </option>
</root>

xaml:

<UserControl x:Class="OptionWPF.DataPane"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="3*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <DataGrid AutoGenerateColumns="False"
              Grid.Row="0"
              RowHeaderWidth="0"
              AlternationCount="2"
              x:Name="DGrid"
              ItemsSource="{Binding Path=Elements[option]}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path = Elements[bid].Value}"
                              Header="Bid" IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding Path=Elements[ask].Value}"
                              Header="Ask" IsReadOnly="True"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="button2" Grid.Row="1" Click="button_Click"/>
</Grid>
</UserControl>

cs:

private void button_Click(object sender, RoutedEventArgs e) 
    {
        XElement xdoc = new XElement("root");
        YahooData data = new YahooData("AAPL");            
        IEnumerable<XElement> doc = data.Document;
        xdoc.Add(doc);
        DGrid.DataContext = xdoc;
    }

您几乎做到了,但有一个小问题-Binding for column will be a collection of XElements(因为您绑定到了Elements集合)。你需要拿到first index value,你就可以出发了。

这将起作用-

<DataGrid.Columns>
   <DataGridTextColumn Binding="{Binding Path = Elements[bid][0].Value}"
                       Header="Bid" IsReadOnly="True"/>
   <DataGridTextColumn Binding="{Binding Path=Elements[ask][0].Value}"
                       Header="Ask" IsReadOnly="True"/>
</DataGrid.Columns>

最新更新