如何以编程方式调用treeView.SelectedItemChanged

时间:2013-08-20 12:59:32

标签: c# wpf treeview selecteditemchanged

在我的程序中,我想使用c#代码隐藏来调用SelectedItemChanged事件,我只是不确定要作为参数传递什么。这是针对TreeViewItem

//Gets selected item in TreeView
private void TreeOne_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    MainWindowViewModel.SelectedItem = e.NewValue as TreeViewItem;
}

//I'm calling the SelectedItemChanged event from a RightButtonDown event
private void TreeOne_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TreeOne_SelectedItemChanged(/* What would go here? **/);
}

此外,当我尝试构建这个时,我收到这个编译器错误,这几乎导致了这个问题......

  

方法TreeOne_SelectedItemChanged没有重载需要'0'参数

我希望这是一个简单的问题,但如果我没有提供足够的信息,或者说不够清楚,请告诉我。

3 个答案:

答案 0 :(得分:1)

添加@Bart Friederichs的回答并假设您有TreeView的引用,您可以添加以下方法:

private void SetSelectedItem()
{
     MainWindowViewModel.SelectedItem = TreeOne.SelectedItem;
}

然后你可以随便在任何地方调用它:

private void TreeOne_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    SetSelectedItem();
}

private void TreeOne_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    SetSelectedItem();
}

答案 1 :(得分:0)

通常的设计模式是调用某种处理方法,而不是“手动”触发事件:

private TreeOne_SelectedItemChaned(object sender, 
                        RoutedPropertyChangedEventArgs<object> e) {
    processChange();
}

然后,从您的代码开始,您只需致电processChange(),无需致电TreeOne_SelectedItemChanged

答案 2 :(得分:0)

尝试致电

TreeOne_SelectedItemChanged(null,null);