鉴于我的 MVVM 应用程序中的两个模型:
MyFolder 包含文件列表 (MyFiles):
public class MyFolder
{
public string Path { get; set; }
public int Id { get; set; }
public List<MyFile> FilesList { get; set; }
}
public class MyFile
{
public string Path { get; set; }
public int Size { get; set; }
}
在我的 Viewmodel 中,我有一个带有文件夹的 ObservableCollection:
public ObservableCollection<MyFolder> FoldersList { get; set; }
我在一个 ListBox 中查看文件夹,在另一个 ListBox 中我显示所选文件夹的文件列表(也在 ViewModel 中定义):
私有(private)MyFolder selectedFolder;
public MyFolder SelectedFolder
{
get { return selectedFolder; }
set
{
selectedFolder = value;
OnPropertyChanged(nameof(SelectedFolder));
}
}
我需要的是能够选择列表框中显示的一些文件以对它们执行一些操作(比如更改它们的扩展名)
<ListBox ItemsSource="{Binding Path=FoldersList.FilesList}" SelectedItem="{Binding Path=SelectedFolder, Mode=OneWayToSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox IsChecked="{Binding ????}"/>
<Label VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Content="{Binding Path=Path}">
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我可以向 MyFiles 类添加一个属性,如 bool Selected,然后将此属性绑定(bind)到 CheckBox。
但是,这是在 MVVM 模式中执行此操作的方法吗?
或者我应该怎么做?
非常感谢任何想法。 提前致谢
最佳答案
您所描述的方法对我来说似乎是合法的,但是请注意,您还必须在 MyFile 类中实现 INotifyPropertyChanged,否则您对复选框的绑定(bind)将不起作用。
<ListBox ItemsSource="{Binding Path=FoldersList.FilesList}" SelectedItem="{Binding Path=SelectedFolder, Mode=OneWayToSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox IsChecked="{Binding Checked}"/>
<Label VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Content="{Binding Path=Path}">
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class MyFile : INotifyPropertyChanged
{
public void SetPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
public string Path { get; set; }
public int Size { get; set; }
private bool _checked = false;
public bool Checked
{
get {return _checked;}
set
{
_checked = value;
SetPropertyChanged("Checked");
}
}
关于c# - 检查绑定(bind)到 MVVM 应用程序中的 ObservableCollection 的列表框中的选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48418050/