1
votes

i implemented a MVVM TreeView in my code. i want that the focus will be on the newest TreeViewItem in my tree (i keep on updating the treeview) i tried the following:

<TreeView ItemsSource="{Binding NotificationViewModel}" Name="MainTree">
    <TreeView.ItemContainerStyle>
        <!-- This Style binds a TreeViewItem to a NotificationViewModel. -->
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            <Setter Property="IsFocused" Value="{Binding IsFocused, Mode=TwoWay}" />
        </Style>
    </TreeView.ItemContainerStyle>

and in the ViewModel:

// Constructor
public NotificationListViewModel(Notification notification)
{
    _notification = notification;

    _activityListViewModel = new ObservableCollection<ActivityListViewModel>();

    _isSelected = true;

    _isFocused = true;
}


private bool _isFocused;

public bool IsFocused
{
    get { return _isFocused; }
    set
    {
        if (value != _isFocused)
        {
            _isFocused = value;
            this.OnPropertyChanged("IsFocused");
        }
    }
}

but i get the following error:

Error 1 The Property Setter 'IsFocused' cannot be set because it does not have an accessible set accessor. Line 115 Position 29. C:\My Visual Studio Projects\MainTreeView\View\NotificationListView.xaml 115 29

why i can't implement the focus like IsSelected and IsExpanded ?

1

1 Answers

2
votes

The property IsFocused is readonly and can not, therefore, set focus to the control. See UIElement.IsFocused on MSDN for a bit more detail.

You could instead use the Focus() method on your treeview.