Reputation: 317
I have binded an XML file to my ListBox using the XmlDataProvider in my XAML file. Is it possible to add or delete items programatically without having to convert to an IObservableCollection, clearing the itemssource, making the changes and then setting the itemssource back to the collection?
Upvotes: 0
Views: 161
Reputation: 89285
Document property of XmlDataProvider is standard XmlDocument object. So you can add, remove, or modify item the same way you do it for XML file abstracted using XmlDocument
. You can find many resources on net explaining how to deal with XmlDocument
. So, this is just simple example adapted from CodeProject article :
the XAML :
<ListBox x:Name="TeamsListBox" Margin="0,0,0,20" DockPanel.Dock="Left"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True"
Visibility="Visible" SelectionMode="Single">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding XPath=Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.DataContext>
<XmlDataProvider x:Name="TeamData" Source="Teams.xml" XPath="Teams/Team" />
</ListBox.DataContext>
</ListBox>
the XML :
<Teams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Team>
<Id>1</Id>
<Name>Arizona Cardinals</Name>
<Conference>NFC West</Conference>
</Team>
<Team>
<Id>2</Id>
<Name>Atlanta Falcons</Name>
<Conference>NFC South</Conference>
</Team>
</Teams>
Sample code to remove first team programmatically :
var xmlData = (XmlDataProvider) TeamsListBox.DataContext;
var node = xmlData.Document.DocumentElement["Team"].SelectSingleNode("//Team[./Id='1']");
node.ParentNode.RemoveChild(node);
NB: It is better if you provide more context (relevant code you already have) in your future questions, so people can focus on answering the actual question and can skip process of recreate a context.
Upvotes: 1