2
I have a question, I have a code that creates a Treeview dynamically through a code c#. A TreeView
was created in WPF.
My goal is to create a function that opens an item XML
and created a TreeView
, and then it is possible to change a node of that TreeView
and it be edited directly on XML
.
So the first part I successfully concluded, which is the opening of the XML
in a TreeView
.
Follows the code:
public partial class MainWindow : DXRibbonWindow
{
//fazer diagrama depois.
private TreeViewItem tree = new TreeViewItem();
private OpenFileDialog dlg = new OpenFileDialog();
private XmlDocument XMLdoc = new XmlDocument();
public MainWindow()
{
InitializeComponent();
}
private void AbrirDispositivoClick(object sender, ItemClickEventArgs e)
{
//Deixando a tree view habilitada.
tvDispositivo.Visibility = Visibility.Visible;
//Abrir arquivos com extensão .xml
dlg.CheckFileExists = true;
dlg.Filter = "XML Files (*.xml)|*.xml";
dlg.Multiselect = false;
if (dlg.ShowDialog() != true) { return; }
try
{
XMLdoc.Load(dlg.FileName);
}
catch (XmlException)
{
MessageBox.Show("O arquivo XML é invalido!");
return;
}
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
XmlReader reader = XmlReader.Create(dlg.FileName, settings);
tree = new TreeViewItem();
tree.Header = "Dipositivo";
tvDispositivo.Items.Add(tree);
BuildArvore(reader, tree);
}
private void BuildArvore(XmlReader reader, TreeViewItem TreeViewItem)
{
TreeViewItem NovoNodo = new TreeViewItem();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
NovoNodo.Header = reader.Value;
TreeViewItem.Items.Add(NovoNodo);
break;
case XmlNodeType.EndElement:
TreeViewItem = (TreeViewItem)TreeViewItem.Parent;
break;
case XmlNodeType.Element:
if (!reader.IsEmptyElement)
{
NovoNodo.Header = reader.Name;
TreeViewItem.Items.Add(NovoNodo);
TreeViewItem = NovoNodo;
}
else
{
NovoNodo.Header = reader.NodeType.ToString();
TreeViewItem.Items.Add(NovoNodo);
}
break;
default:
NovoNodo.Header = reader.NodeType.ToString();
TreeViewItem.Items.Add(NovoNodo);
break;
}
NovoNodo = new TreeViewItem();
}
}
private void EditarNodo(object sender, MouseButtonEventArgs e)
{
if (tvDispositivo.SelectedItem is TreeViewItem)
{
TreeViewItem item = tvDispositivo.SelectedItem as TreeViewItem;
string texto = item.Header.ToString();
item.Header = new TextBox()
{
Text = texto
};
}
}
The event EditarNodo
, is so that with a double click I enable a TextBox
at the location of the selected node.
What I lack now is the possibility to edit this node and finish by pressing enter. I looked for some examples but found nowhere. Someone there knows how I can do it in code . Cs and not in XAML?
Below is the XAML:
<TreeView x:Name="tvDispositivo" Visibility="Hidden" MouseDoubleClick="EditarNodo" />