【发布时间】:2017-03-09 13:06:17
【问题描述】:
我正在尝试为我的应用程序创建一个TreeView。这是我第一次将 TreeView 与 MVVM 结构一起使用,从各方面来看,绑定都在正常工作和显示。
但是:
如何获得选择,以便在用户选择某些内容后执行一些逻辑?
我认为SubSection class 中的TextValue 属性会触发PropertyChanged,但事实并非如此,所以我只能摸不着头脑。
这是我可以为这个问题编写的最简化的代码集:
在ViewModelBaseclass中使用PropertyChanged这样的设置
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
VeiwModel:
public class ShiftManagerViewModel : ViewModelBase
{
public ShiftManagerViewModel()
{
Departments = new List<Department>()
{
new Section("Section One"),
new Section("Section Two")
};
}
private List<Section> _sections;
public List<Section> Sections
{
get{return _sections;}
set
{
_sections = value;
NotifyPropertyChanged();
}
}
}
课程:
public class Section : ViewModelBase
{
public Section(string depname)
{
DepartmentName = depname;
Courses = new List<SubSection>()
{
new SubSection("SubSection One"),
new SubSection("SubSection One")
};
}
private List<SubSection> _courses;
public List<SubSection> Courses
{
get{ return _courses; }
set
{
_courses = value;
NotifyPropertyChanged();
}
}
public string DepartmentName { get; set; }
}
public class SubSection : ViewModelBase
{
public SubSection(string coursename)
{
CourseName = coursename;
}
public string CourseName { get; set; }
private string _vTextValue;
public string TextValue
{
get { return _vTextValue; }
set
{
_vTextValue = value;
NotifyPropertyChanged();
}
}
}
还有 XAML:
<Window.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Courses}" DataType="{x:Type viewModels:Section}">
<Label Content="{Binding DepartmentName}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding TextValue}" DataType="{x:Type viewModels:SubSection}">
<Label Content="{Binding CourseName}" />
</HierarchicalDataTemplate>
</Window.Resources>
有人能指出我正确的方向吗?
【问题讨论】:
-
“用户选择了一些东西” ==
TreeView.SelectedItem更改。在TreeView.SelectedItem和顶级viewModel 属性之间创建一个绑定,并在该属性的设置器中执行一些逻辑 -
@ASh,我也是这么想的,但是
HierarchicalDataTemplate中没有SelectedItem可以绑定???谢谢 -
TreeView.SelectedItem:<TreeView SelectedItem="{Binding Path=???}" ... -
@ASh,我一直在寻找那个,唯一接近的是
SelectedValuePath="{Binding Path=???},这显然不起作用。
标签: wpf xaml mvvm data-binding