WPF Treeview delete operation [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
I am working on WPF TreeViews. I am able to add the new Items under tree, but I am not able to delete them from the list. In my code I am trying to get the index of the selected tree item and trying to Remove it. But the code is returning Index "-1". This results in an ArgumentOutOfRangeException.
Please help to fix this.
<Window x:Class="MyTreeStructure.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="ADD" Height="23" HorizontalAlignment="Left" Margin="211,50,0,0"
Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<TreeView Height="200" HorizontalAlignment="Left" Margin="27,12,0,0" Name="treeView1"
VerticalAlignment="Top" Width="120" >
<TreeViewItem Name="Parent" Header="My Tree Content">
</TreeViewItem>
</TreeView>
<TextBox Height="23" HorizontalAlignment="Left" Margin="211,12,0,0" Name="textBox1"
VerticalAlignment="Top" Width="120" />
<Button Content="Delete" Height="23" HorizontalAlignment="Left" Margin="211,79,0,0"
Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />
</Grid>
</Window>
namespace MyTreeStructure
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
TreeViewItem temp = new TreeViewItem();
temp.Header = textBox1.Text;
Parent.Items.Add(temp);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = treeView1.SelectedItem.ToString();
Parent.Items.RemoveAt(treeView1.Items.IndexOf(treeView1.SelectedItem));
**// Here I am getting exception. What should be the code here ??**
}
}
}

below line is having the problem
treeView1.Items.IndexOf(treeView1.SelectedItem))
Since treeview1 is only having one node 'Parent' , rest of the node which you have added is in the node called 'Parent'.
So if you trying to get the index for a node in treeView1.Items it will return -1 except for the node called 'Parent' for which it will return 0.
so you nned to modify the code for removing a node as below.
private void button2_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = treeView1.SelectedItem.ToString();
int index = treeView1.Items.IndexOf(treeView1.SelectedItem));
if(index < 0)
{
index = Parent.Items.IndexOf(treeView1.SelectedItem));
}
if(index > 0)
{
Parent.Items.RemoveAt(index);
}
}

I am not familiar with WPF but in WinForms your approach will cause errors. The first one could be a result of the internal numeration of items. It is like this:
0
-0
-1
-2
1
-0
-0
-1
-1 ...
Another stumbling stone is that IndexOf returns -1 (as you mentioned) if the item was not found. You have to check if the value is -1 first, then navigate to the correct Sublist in Treeview.Nodes.Nodes... and finally call RemoveAt().
I Hope this was helpful
Patrick

Here's my two cents worth. This code is working on my machine.
TreeViewItem t;
private void button2_Click(object sender, RoutedEventArgs e)
{
// Delete the node
Parent.Items.RemoveAt(Parent.Items.IndexOf(t));
}
private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
// Get the selected node
t = (TreeViewItem)(((TreeView)e.Source).SelectedItem);
}

<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0" Name="textBox1" VerticalAlignment="Top" Width="127" />
<Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="76" Click="button1_Click">Add Item</Button>
<Button Height="23" Margin="226,14,124,0" Name="DeleteButton" VerticalAlignment="Top" Click="DeleteButton_Click">Delete Item</Button>
<TreeView Margin="10,100,0,13" Name="TreeView1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200">
<TreeViewItem x:Name="Parent" Header="Cold Drinks">
<TreeViewItem Header="Coke"></TreeViewItem>
<TreeViewItem Header="Pepsi"></TreeViewItem>
<TreeViewItem Header="Orange Juice"></TreeViewItem>
<TreeViewItem Header="Milk"></TreeViewItem>
<TreeViewItem Header="Iced Tea"></TreeViewItem>
<TreeViewItem Header="Mango Shake"></TreeViewItem>
</TreeViewItem>
</TreeView>
</Grid>
private void button1_Click(object sender, RoutedEventArgs e)
{
TreeViewItem newChild = new TreeViewItem();
newChild.Header = textBox1.Text;
Parent.Items.Add(newChild);
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
int index = TreeView1.Items.IndexOf(TreeView1.SelectedItem);
if (index < 0)
{
index = Parent.Items.IndexOf(TreeView1.SelectedItem);
}
if (index >= 0 && ((System.Windows.Controls.TreeViewItem)TreeView1.SelectedItem).Name.Contains("Parent"))
{
TreeView1.Items.RemoveAt(index);
}
else if (index >= 0)
{
Parent.Items.RemoveAt(index);
}
}

Related

Set selected item in WPF ComboBox [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
(I've read similar posts but they all had a twist to them that made the solution different)
I'm porting a WinForms app that used this:
myComboBox.SetSelected(myComboBox.FindString("Some Text"), true);
to select an item programmatically. When porting over to WPF, I tried this but it has no effect (the item does not get selected):
myComboBox.SelectedItem = myComboBox.FindName("Some Text");
What is the correct way to select an existing item in a ComboBox, in WPF?
You have to use SelectedValue. In WPF ComboBox, there are multiple ways to achieve the same thing. So, one syntax to select an item programmatically won't work. There are various ways of adding items to ComboBox.
You can set ItemsSource both declaratively or in code.
You can add ComboBoxItems etc. See Items property in property window to see various item-types available.
If you are using ItemsSource with string values, then you need syntax like : cmb1.SelectedValue = "Name1"
If you are directly adding items like <ComboBox ...> <ComboBoxItem Content="Name1"/> </ComboBox/> , then you need
foreach (ComboBoxItem item in cmb2.Items)
if (item.Content.ToString() == "Name1")
{
cmb2.SelectedValue = item;
break;
}
I have posted a full working sample demonstrating how to select an item programmatically in various scenarios. Sample code (can be used as is) :
Pay attention to last one, where you have to use SelectedValuePath.
Window1.xaml
<Window x:Class="WpfApplicationBlend.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="Window1" Height="411" Width="749">
<Grid>
<Grid Margin="30,27,491,276">
<ComboBox x:Name="cmb1" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" FocusVisualStyle="{DynamicResource StyleFocusDefault}">
<ComboBox.ItemsSource>
<CompositeCollection>
<sys:String>Name1</sys:String>
<sys:String>Name2</sys:String>
<sys:String>Name3</sys:String>
<sys:String>Name4</sys:String>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
<TextBox x:Name="tbInput1" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
</Grid>
<Grid Margin="405,27,111,276">
<ComboBox x:Name="cmb2" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" FocusVisualStyle="{DynamicResource StyleFocusDefault}">
<ComboBoxItem Content="Name1"/>
<ComboBoxItem Content="Name2"/>
<ComboBoxItem Content="Name3"/>
</ComboBox>
<TextBox x:Name="tbInput2" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button2_Click"/>
</Grid>
<Grid Margin="30,207,491,96">
<ComboBox x:Name="cmb3" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" FocusVisualStyle="{DynamicResource StyleFocusDefault}">
<ComboBox.ItemsSource>
<CompositeCollection>
<sys:String>Name1</sys:String>
<sys:Boolean>True</sys:Boolean>
<sys:Int32>123</sys:Int32>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
<TextBox x:Name="tbInput3" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button3_Click"/>
</Grid>
<Grid Margin="405,207,116,96">
<ComboBox x:Name="cmb4" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" SelectedValuePath="Name" DisplayMemberPath="Name">
</ComboBox>
<TextBox x:Name="tbInput4" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button4_Click"/>
</Grid>
</Grid>
</Window>
Window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Collections;
namespace WpfApplicationBlend
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
List<Employee> employees = new List<Employee>()
{
new Employee(){Name="Name1", Age=100},
new Employee(){Name="Name2", Age=101},
};
cmb4.ItemsSource = employees;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
cmb1.SelectedValue = tbInput1.Text;
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
foreach (ComboBoxItem item in cmb2.Items)
if (item.Content.ToString() == tbInput2.Text)
{
cmb2.SelectedValue = item;
break;
}
}
private void Button3_Click(object sender, RoutedEventArgs e)
{
foreach (object item in cmb3.Items)
if (item.ToString() == tbInput3.Text)
{
cmb3.SelectedValue = item;
break;
}
}
private void Button4_Click(object sender, RoutedEventArgs e)
{
cmb4.SelectedValue = tbInput4.Text;
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
}
comboboxName.SelectedIndex = yourIndex;
e.g.
combobox1.SelectedIndex = 2;

check whether there is a focus on the elements

I have 3 textbox. How can i know which one of them has the focus?
if (TextBoxExtendedSearchName.Focus() == false &&
TextBoxExtendedSearchNomenclature.Focus() == false
&& TextBoxExtendedSearchSpecialist.Focus() == false)
{
window.Close();
}
this does not work
I Use WPF
private void TextBox1_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
}
private void TextBox2_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
}
this example not work
I think I understand what the problem is. it does not work when I'm doing it in the event Lost Focus.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBox1_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
else
MessageBox.Show("Yes Focus");
}
private void TextBox2_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
else
MessageBox.Show("Yes Focus");
}
XAml
<Window x:Class="TrainWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="TextBox1" HorizontalAlignment="Left" Height="25" Margin="62,61,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="205" LostFocus="TextBox1_LostFocus"/>
<TextBox x:Name="TextBox2" HorizontalAlignment="Left" Height="23" Margin="62,145,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="205" LostFocus="TextBox2_LostFocus"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="267,249,0,0" VerticalAlignment="Top" Width="96" RenderTransformOrigin="0.5,0.5" Height="37">
<Button.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0.397"/>
<TranslateTransform/>
</TransformGroup>
</Button.RenderTransform>
</Button>
</Grid>
</Window>
this does not work
I understand it's my logical error
try this:
//Logical focus
var focusedControl = FocusManager.GetFocusedElement(this);
//KeyBoard focus
var focusedControl = Keyboard.FocusedElement;
// dummy logic to close the window when all the three textboxes are not focused.
List<TextBox> items=new List<TextBox>();
items.Add(TextBoxExtendedSearchName);
items.Add(TextBoxExtendedSearchNomenclature);
items.Add(TextBoxExtendedSearchSpecialist);
if(!items.Any(o=>o==focusedControl))
{
window.Close();
}
You are using the wrong function. You need to use the IsFocused property to get it a Control has a focus.
See the documentation here: Link
With your code:
if (!TextBoxExtendedSearchName.IsFocused
&& !TextBoxExtendedSearchNomenclature.IsFocused
&& !TextBoxExtendedSearchSpecialist.IsFocused)
{
window.Close();
}
This will Close the window if none of them has a Focus.

Windows phone 8.1 button click arguments

Is there a way to pass arguments on button click in Windows Phone 8.1?
I have a grid of 5x5 buttons, and they should all call the same method but with a different parameter. I am adding a handler like this:
foreach (var child in buttonGrid.Children)
{
Button b = child as Button;
if (b != null)
{
b.Click += Button_Click;
// I want to add an argument to this
}
}
Now the only way I can get the index of the button is by iterating over the whole grid and checking if the sender is equal to the button:
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < buttonGrid.Children.Count; i++)
{
if (sender == buttonGrid.Children[i])
{
DoSomething(i);
return;
}
}
}
It works, but I don't really like this approach. Is there a more efficient way of doing this (other than creating a different method for each of the 25 buttons)?
I tried searching on the internet, but the documentation and examples for Windows Phone are really lacking. If anyone has a good repository of Windows Phone 8.1 tutorials to direct me to, that would also be of help.
You can use Tag property of the button.
For eg.
I'm trying to create a number pad which has 9 buttons with the respective number as the button content and i have set the same thing as the Tag property also.
<StackPanel>
<StackPanel Orientation="Horizontal" >
<Button Content="1" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="1" />
<Button Content="2" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="2" />
<Button Content="3" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="3" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button Content="4" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="4" />
<Button Content="5" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="5" />
<Button Content="6" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="6" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button Content="7" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="7" />
<Button Content="8" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="8" />
<Button Content="9" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="48" FontWeight="Bold" Click="Button_Click" Tag="9" />
</StackPanel>
</StackPanel>
This produces the following output :
In your code behind you can now use the Tag property in the following manner
private void Button_Click(object sender, RoutedEventArgs e)
{
var tag = (sender as Button).Tag;
int t = Convert.ToInt16(tag);
switch (t)
{
case 1:
//Do Something
break;
case 2:
//Do Something
break;
case 3:
//Do Something
break;
case 4:
//Do Something
break;
case 5:
//Do Something
break;
case 6:
//Do Something
break;
case 7:
//Do Something
break;
case 8:
//Do Something
break;
case 9:
//Do Something
break;
default:
break;
}
}
Controls and other elements in XAML have a Tag property that you can set to an arbitrary object value for this kind of thing. Set it when you create the object and then inspect it in the event handler.
A simple solution would be to assign unique numbers to each button and then call the function with this uniquely assigned number as a parameter.
In the function, you could easily use the If-Else blocks to perform the task according to the Unique Number.
The code for 4 buttons becomes something like:-
void func(int unique_number)
{
if(unique_number==1)
{
//perform tasks for button 1
}
if(unique_number==2)
{
//perform tasks for button 2
}
if(unique_number==3)
{
//perform tasks for button 3
}
if(unique_number==4)
{
//perform tasks for button 4
}
}
private void Button_1_Click(object sender, RoutedEventArgs e)
{
func(1); //Call from button 1
}
private void Button_2_Click(object sender, RoutedEventArgs e)
{
func(2); //Call from button 2
}
private void Button_3_Click(object sender, RoutedEventArgs e)
{
func(3); //Call from button 3
}
private void Button_4_Click(object sender, RoutedEventArgs e)
{
func(4); //Call from button 4
}
I hope this makes it somewhat easy and efficient.
While the answers show you how to do this using Tag, this approach is non-convenient for, say 100 buttons.
To achieve your result, you can use closures for the job. Here's how:
// When you're attaching handlers
int i=0;
foreach (var child in buttonGrid.Children)
{
Button b = child as Button;
if (b != null)
{
b.Click += () => {
int z = i++; // You can put a different id generator here as well, like int z = <rand>%<prime> if you want
DoSomething(z); // DoSomething called with corrosponding button id
}
}
}
This approach does not require you to use tags!

use of combobox to appear another combobox C#

I want to make this as, once i select the first item(Student Information) of the first_ComboBox want to appear second_ComboBox.
How can I make this happen
In the cs code
private void first_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void second_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
in XAML
<StackPanel Margin="97,47,171,499" Orientation="Horizontal" Grid.Row="1">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Where You want to Control" VerticalAlignment="Top" Height="82" Width="463" FontSize="36"/>
<ComboBox x:Name="first_ComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="560" Height="42" SelectionChanged="first_ComboBox_SelectionChanged">
<x:String>Student Information</x:String>
<x:String>Staff Information</x:String>
<x:String>Academic Information</x:String>
</ComboBox>
</StackPanel>
<StackPanel Margin="97,172,171,374" Orientation="Horizontal" Grid.Row="1">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Select the Field" VerticalAlignment="Top" Height="82" Width="463" FontSize="36"/>
<ComboBox x:Name="second_ComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="560" Height="42" SelectionChanged="second_ComboBox_SelectionChanged">
<x:String>Student Name</x:String>
<x:String>Student Address</x:String>
</ComboBox>
</StackPanel>
On your Form main, you can set the visibility of Second Combobox to be false, and then on the first combobox selection changed set it to true, Something like this
public MainWindow()
{
InitializeComponent();
second_ComboBox.Visibility = Visibility.Collapsed;
}
private void first_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selecteditem = first_ComboBox.SelectedItem as string;
if (selecteditem != null)
{
second_ComboBox.Visibility = Visibility.Visible;
}
}
on initialization make second combobox visiblity hidden
public MainWindow()
{
InitializeComponent();
second_ComboBox.Visibility = Visibility.Collapsed;
}
private void first_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
first_ComboBox.Visibility = System.Windows.Visibility.Visible;
}

WPF: Adding ContexMenu to Dynamically Created Tree

Hi all I am trying to add ContexMenu into my Dynamically generated Tree.
Below is my Code For generating Tree.
I need to add ContexMenu for :
NEW:
EDIT:
DELETE
on MouseClick I should be able to perform the same operation of clicking the Respective Buttons.
Can any body help in completing the code.
XML:CODE
<Window x:Class="NewTree_DynamicNode.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="TestsTreeViewPageFunction_Loaded">
<Grid>
<TreeView Name="treeFileSystem" >
<TreeViewItem Header="Suite" Name="MYTree" Tag="hi" IsExpanded="True">
<TreeViewItem Name="treeFileSystem1" />
</TreeViewItem>
</TreeView>
<TextBox Name="textBox1" Height="23" HorizontalAlignment="Left" Margin="121,150,0,0" VerticalAlignment="Top" Width="120" />
<Button Content="New" Height="23" HorizontalAlignment="Left" Margin="12,121,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="New_Click" />
<Button Content="Edit" Height="23" HorizontalAlignment="Left" Margin="12,150,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="Edit_Click"/>
<Button Content="Copy" Height="23" HorizontalAlignment="Left" Margin="12,179,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="Copy_Click"/>
</Grid>
</Window>
C# CODE:
private void TestsTreeViewPageFunction_Loaded(object sender,
RoutedEventArgs e)
{
this.MYTree.Items.Clear();
for (int j = 1; j < 4; j++)
{
TreeViewItem Case = new TreeViewItem();
Case.Header = "Case "+j.ToString();
Case.IsExpanded = true;
Case.Items.Add(Trythis());
this.MYTree.Items.Add(Case);
}
}
private TreeViewItem Trythis()
{
TreeViewItem Step = new TreeViewItem();
for (int i = 0; i < 5; i++)
{
Step.Header = "Steps " + i.ToString();
}
return Step;
}
private void New_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "New Button Clicked";
}
private void Edit_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Edit Button Clicked";
}
private void Copy_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Copy Button Clicked";
}
EDIT:
I am looking for a solution where I should be able to add or limit the ContexMenu to TreeItem based on there Header information.
You can use style to set common ContextMenu property:
<TreeViewItem Header="Suite" Name="MYTree" Tag="hi" IsExpanded="True">
<TreeViewItem.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="New" />
<MenuItem Header="Edit" />
<MenuItem Header="Delete" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeViewItem.Resources>
<TreeViewItem x:Name="treeFileSystem1" />
</TreeViewItem>
Or you can add context menu in code: before line this.MYTree.Items.Add(Case);
you can add something like this:
var menu = new ContextMenu();
menu.Children.Add(new MenuItem{Header = "Save"});
menu.Children.Add(new MenuItem{Header = "Load"});
Case.ContextMenu = menu;

Categories