Getting title in treeviewItems
I created a tree structure and now I want to get the title name as a string for use in the ViewModel. The command works, but I cannot get the header name to pass as a parameter in the method.
How do I get the title name every time I select a new new treeViewItem?
XAML
<TreeView Name="EquipmentTreeView">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<i:InvokeCommandAction
Command="{Binding SelectItemCommand}"
CommandParameter="{Binding SelectedItem, ElementName=EquipmentTreeView}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeViewItem Header="Camera">
<TreeViewItem Header="Digital Camera">
</TreeViewItem >
<TreeViewItem Header="Film Camera">
<TreeViewItem Header="35mm Film Sound Camera"></TreeViewItem>
<TreeViewItem Header="35mm Film MOS Camera"></TreeViewItem>
<TreeViewItem Header="Film Magazines"></TreeViewItem>
</TreeViewItem>
....
ViewModel (parameter not working)
public class EquipmentManagerViewModel : NotifyUIBase
{
public EquipmentManagerViewModel()
{
SelectItemCommand = new RelayCommand(() => GetItemHeader(SelectedItem));
}
public RelayCommand SelectItemCommand { get; private set; }
private void GetItemHeader(string selectedHeader)
{
MessageBox.Show(selectedHeader);
}
}
source to share
I don't know the implementation of your RelayCommand, but you must pass the Parameter RelayCommand as a parameter to your GetItemHeader method. You are passing in a SelectedItem which is undefined. Without any changes to you xaml, do the following:
public EquipmentManagerViewModel()
{
SelectItemCommand = new RelayCommand(tvi => GetItemHeader(((TreeViewItem)tvi).Header.ToString()));
}
But then I would rename the method because it doesn't do what I expected. It doesn't give you an ItemHeader! You extract the title and pass it to a method, the method displays a MessageBox with text as a parameter.
Edit
@Almulo's comment leads me to the following changes:
In Xaml as @Mike suggests:
<i:InvokeCommandAction
Command="{Binding SelectItemCommand}"
CommandParameter="{Binding SelectedItem.Header, ElementName=EquipmentTreeView}"/>
and in the ViewModel:
public EquipmentManagerViewModel()
{
SelectItemCommand = new RelayCommand<String>(obj => GetItemHeader(obj.ToString()));
}
public RelayCommand<String> SelectItemCommand { get; private set; }
private void GetItemHeader(string selectedHeader)
{
MessageBox.Show(selectedHeader);
}
based on what your RelayCommand can handle CommandParameter.
source to share