Select topnode by default in Treeview wpf MVVM
I 开发者_StackOverflow中文版have a Treeview which is doing lazy loading. I used MVVM. I wanted to select the top node of the tree by default when my application launches.
I think there is a better way... Just ceate a class that inherits from System.Windows.Controls.TreeView and override OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e). And in this method put this code:
if (base.SelectedItem == null)
{
if(base.Items.Count != 0)
{
(base.ItemContainerGenerator.ContainerFromItem(base.Items[0]) as TreeViewItem).IsSelected = true;
}
}
base.OnItemsChanged(e);
And that's it.
The easiest way to do this is use a style with an IsSelected
property:
<Style x:Key="SelectableTreeViewItem" TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
Then expose this property in your model, or more specifically in the object that you bind to for your top level node.
public class MyTopLevelFoo
{
public bool IsSelected { get; set; }
}
...and set it to true when you initially load:
IsSelected = true;
Just use Loaded Event
private void tvComponents_Loaded(object sender, RoutedEventArgs e)
{
(tvComponents.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem).IsSelected = true;
}
精彩评论