How to use OpenFileDialog?
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "xml files (*.xml)|*.xml";
if (ofd.ShowDialog()==true)
{
string fileContent = ofd.File.OpenText().ReadToEnd();
// do some thing
}
How to use SaveFileDialog?
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "xml files (*.xml)|*.xml";
if (sfd.ShowDialog() == true)
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(fileString); // fileString would be something you want to save to the file
using (Stream fs = (Stream)sfd.OpenFile())
{
fs.Write(fileBytes, 0, fileBytes.Length);
fs.Close();
}
}
How to parse XML?
To parse a XML file like this:
<List type="DotNetIdeas.CF.RecipeBox.RecipeBox">
<category name="Breakfast" order="0">
<item name="pan cake"/>
<item name="milk"/>
<category name="Desert" order="1">
</List>
You can do something like this:
XDocument xd = XDocument.Parse(xml);
XElement node = xd.Root;
var categories = (from category in xd.Descendants("category")
select new Category()
{
Name = category.Attribute("name").Value,
Order = Convert.ToInt32(category.Attribute("order").Value),
Items = FromXml(category.Elements("item"))
}).ToList();
If you happened to be like me, migrating the code from some old programs, don’t forget to add “using System.Linq” which is in System.Core.dll. Otherwise you will get a compiler error.
How to use TreeView?
To create a TreeView like this one, you will need to use HierarchicalDataTemplate. It is in System.Windows.Controls. So add the following namespace first:
xmlns:control="clr-namespace:System.Windows;assembly=System.Windows.Controls"
<controls:TreeView x:Name="ingredientList" Height="330" Width="248" Canvas.Left="17" Canvas.Top="18">
<controls:TreeView.ItemTemplate>
<control:HierarchicalDataTemplate ItemsSource="{Binding Items}">
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="itemCheckbox" IsChecked="{Binding ItemChecked, Mode=TwoWay}"/>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</control:HierarchicalDataTemplate>
</controls:TreeView.ItemTemplate>
</controls:TreeView>
private void ingredientName_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
BindingExpression bExp = ingredientName.GetBindingExpression(TextBox.TextProperty);
if (bExp != null)
{
bExp.UpdateSource();
}
}