WPF and C# - Gridview Row selection and XML Datasource - how to make the connection?
I have开发者_Python百科 a GridView defined like this :-
< ListView Name="chartListView" SelectionChanged="chartListView_SelectionChanged">
< ListView.View>
< GridView>
< GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="250"/>
< GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" Width="60"/>
< GridViewColumn Header="Default Font" DisplayMemberBinding="{Binding defaultFontName}" Width="100"/>
< GridViewColumn Header="Size" DisplayMemberBinding="{Binding defaultFontSize}" Width="40"/>
< GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="100"/>
</GridView>
</ListView.View>
</ListView>
and I populate the GridView with an XML datasource like this
XDocument xml = XDocument.Load(@"D:\devel\VS\pchart\charts.xml");
var query = from p in xml.Elements("charts").Elements("chart")
select p;
foreach (var record in query)
{
chartListView.Items.Add(new { Name = record.Attribute("Name").Value, Type = record.Attribute("Type").Value, defaultFontName = record.Attribute("defaultFontName").Value, defaultFontSize = record.Attribute("defaultFontSize").Value, ID = record.Attribute("ID").Value });
}
My question is, when a user clicks on a row in the GridView, and the function chartListView_SelectionChanged is triggered, how do select the corresponding record in my XML datasource, so that I can manipulate the correct/selected data?
Thanks, Will.
I would not fill the listview hardcoded the way you did it. What you'd normally do is bind the ListView to a datasource (the xml) and let WPF databinding handle the update of the XML data automatically. To do this you could create a DataSet from your XML and then bind that using ListView.ItemsSource. You would then create a DataTemplate to define the visual representation of a record in your xml. This could be input controls that'd allow you do directly edit the record within your listview. If you prefer a master-detail style view you would bing the detail view to the current item of your listview (e.g. UserControl.DataContext={Binding CurrentItem, ElementName=myListView}). The rest will be handled by WPF.
UPDATE: Here is an example how you could even bind direcly to your XDocument, so so you do not necessarily have to use DataSets.
精彩评论