I am trying to get the selected item from my TreeView but having some problem.
I am following MVVM archetecture. My ViewModel contains a collection of a class which is in my Model. So I have binded the ItemSource of TreeView with that collection. I want to bind the selectedItem of my TreeView to an item of the binded collection. How do I do that? Here is the code for SelectedItem and IsSelected Property.
private static sourceData _selectedItem = null;
/// <summary>
/// Selected Item in the tree
/// </summary>
public static sourceData SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
}
}
}
private bool _isSelected;
/// <summary>
/// Get/Set for Selected node
/// </summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
if (_isSelected)
{
SelectedItem = this;
OnPropertyChanged("IsSelected");
}
}
}
}
/// <summary>
/// Property changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Property changed event handler
/// </summary>
/// <param name="propertyName"></param>
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
When I debug this, int SelectedItem = this;
'this' pointer contains the collection to which my treeview is binded. I needed to have a SelectedDataSource so that I could assign it to the selected Item. How can I make my TreeView return me the selectedItem in the collection??
FYi, this is my XAML code for TreeView
<TreeView Margin="5,0,0,0" ItemsSource="{Binding SourceData}" Width="390">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding DataContext.IsSelected, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu Name="contextMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" >
<MenuItem Name="menuItem" Header="Rename" Command="{Binding RenameCommand}" />
</ContextMenu>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
PS: If I write the above code in my Model, I get everything working perfectly fine. But I can not write the above code in Model, it has to be in VM.