我已根据以下文章实现了树视图的SelectedItem:Data binding to SelectedItem in a WPF Treeview
SelectedItem非常完美,它真实地反映了所选项目。
现在我想与所选项目互动,但我不确定如何。我可以创建一个BindableSelectedItemBehavior类的实例,但这不是包含我正在寻找的数据的实例。如何访问持有treeview的SelectedItem的类实例?
这是我的代码的一个亮点:
namespace QuickSlide_2._0
{
public class BindableSelectedItemBehavior : Behavior<TreeView>
{
...
}
public partial class Window1 : Window
{
.....
private void New_subject_Click(object sender, RoutedEventArgs e)
{
// here the code to read the instance of the class BindableSelectedItemBehavior and interact
// with the selectedItem when I click on the button
}
}
}
也许我完全看错了方向。非常感谢您的帮助!
答案 0 :(得分:0)
您希望使用MVVM
,以便绑定行为的依赖项属性,然后您可以访问您所做的SelectedItem
的值。
public class BindableSelectedItemBehavior : Behavior<TreeView>
{
//Dependency property called SelectedTreeViewItem register it
}
public partial class Window1 : Window
{
public Window1()
{
DataContext = new WindowViewModel();
}
private void New_subject_Click(object sender, RoutedEventArgs e)
{
// here the code to read the instance of the class BindableSelectedItemBehavior and interact
// with the selectedItem when I click on the button
var windowViewModel = DataContext as WindowViewModel;
var selectedItem = windowViewModel.SelectedItem;
}
}
public class WindowViewModel()
{
public object SelectedItem { get; set; } // You want to change object to the type you are expecting
}
和View
<TreeView>
<TreeView.Behaviors>
<BindableSelectedItemBehavior SelectedTreeViewItem="{Binding SelectedTreeViewItem,Mode=TwoWay}">
</...>
</...>