2013-12-09 130 views
0

我想使用来自XElement的数据填充位于usercontrol内的数据网格。 datagrid构建行,但其中没有值显示。我在输出窗口中显示System.Windows.Data Error: 40 : BindingExpression path error: 'Value' property not found on 'object'。不知道我做错了什么,我看过几个使用这种方法的例子。我认为它可能与datagrid的位置有关,该位置位于usercontrol内,但不确定。使用XElement填充WPF数据网格

的的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; 
    } 
+1

你应该元素中使用索引。如: - Elements [bid] [1] .Value。 –

回答

1

你就要成功了,但一个小问题 - Binding for column will be a collection of XElements(因为你绑定元素集合) 。你需要得到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> 
+1

修好了!谢谢!! – Wallace