我正在努力争取某些事情并希望有人可以提供有关如何实现这一目标的建议:
我编写了一个看起来像文件浏览器的UserControl,左侧是带有磁盘驱动器和文件夹的TreeView(每个项目都有一个复选框),一旦选择了左侧的TreeViewItem,右侧应显示ListView中该目录的内容,还有每个文件的复选框。
TreeView绑定在ViewModel中,并且有许多子节点和子节点。这很好用。然而,右侧应该只有1级儿童而不是子级儿童。
我在ViewModel中获得了“IsSelected”事件,但当然我在左侧有一个对当前所选TreeViewItem的引用,这与右侧的主级ListView完全无关,我需要在那一点填写数据。我怎样才能到达右侧的主级ListView,有没有办法创建一个全局的lvMain或者我可以从ViewModel中访问的东西,或者我是否以错误的方式使用所有这些并且我需要2个ViewModel?欢迎任何提示!
编辑:这是所需结果的图像,它是非MVVM版本,我现在转换为使用viewmodel的控件,以便添加额外的功能:
一些XAML代码段:
<TreeView Name="myTreeView" ItemsSource="{Binding tvChildren}" ItemTemplate="{StaticResource CheckBoxItemTemplate}" Height="Auto" Width="Auto"></TreeView>
...
<ListView x:Name="myListView" FontWeight="Normal" ItemsSource="{Binding lvChildren}" Width="Auto" HorizontalAlignment="Stretch">
UserObject代码段:
public FileExplorer()
{
InitializeComponent();
try
{
// Initially fill TreeView (left side of FileExplorer) with local drives:
DriveInfo[] drives = DriveInfo.GetDrives();
ViewModel dummyNode = null;
int i = 0;
foreach (DriveInfo drive in drives)
{
if (drive.DriveType != DriveType.CDRom)
{
ViewModel node = new ViewModel();
tvMainNode.tvChildren.Add(node);
node.Text = drive.Name;
node.FullDir = drive.Name;
node._parent = tvMainNode;
// Add a blanc child so the toggle buttons are generated:
tvMainNode.tvChildren[i].tvChildren.Add(dummyNode);
i++;
}
}
}
catch { return; }
DataContext = this;
}
ViewModel代码段:
private readonly ObservableCollection<ViewModel> _tvChildren = new ObservableCollection<ViewModel>();
private readonly ObservableCollection<ViewModel> _lvChildren = new ObservableCollection<ViewModel>();
void SetIsSelected(bool value)
{
if (value == _isSelected) { return; }
_isSelected = value;
// This is obviously not working:
ViewModel test = new ViewModel();
this.lvChildren.Clear();
test.Naam = "bla";
this.lvChildren.Add(test);
}