专注于MVVM TreeView

时间:2011-12-29 22:17:42

标签: wpf mvvm treeview focus

我在我的代码中实现了一个MVVM TreeView。 我希望焦点将放在我树中的最新TreeViewItem上(我继续更新树视图) 我尝试了以下方法:

<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>

并在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");
        }
    }
}

但是我收到以下错误:

  

错误1无法设置属性设置器“IsFocused”,因为它确实如此   没有可访问的集访问器。第115行位置29. C:\我的   视觉工作室   Projects \ MainTreeView \ View \ NotificationListView.xaml 115 29

为什么我不能像IsSelected和IsExpanded那样实现焦点?

1 个答案:

答案 0 :(得分:1)

属性IsFocused是只读的,因此无法将焦点设置为控件。有关详细信息,请参阅UIElement.IsFocused on MSDN

您可以在树视图中使用Focus()方法。