[英]Check for selected items in a ListBox bound to an ObservableCollection in a MVVM application
給定我的MVVM應用程序中的兩個模型:
包含文件列表( MyFiles )的MyFolder :
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中定義):
私人MyFolder selectedFolder;
public MyFolder SelectedFolder
{
get { return selectedFolder; }
set
{
selectedFolder = value;
OnPropertyChanged(nameof(SelectedFolder));
}
}
我需要的是能夠選擇ListBox中顯示的某些文件來對它們執行一些操作(比如說更改其擴展名)
<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,然后將此屬性綁定到CheckBox。
但是,這是在MVVM模式中做到這一點的方法嗎?
還是我應該怎么做?
任何想法真的很感激。 提前致謝
您所描述的方法對我來說似乎是合法的,但是請注意,您還必須在MyFile類中實現INotifyPropertyChanged,否則您對復選框的綁定將不起作用。
<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");
}
}
我建議擁有2個視圖模型
FolderViewModel
和FileViewModel
,它們本質上都是模型類的包裝,但是也可以具有UI Related功能。
因此您的fileViewModel將具有一個稱為IsSelected
的屬性,或者您需要的其他任何屬性, FolderViewModel
將具有FileViewModel
的集合。 您可以通過使其更可擴展和更強大的MVVM,從fileViewModel本身以及那里觸發屬性更改
public class Folder
{
//Model PROPERTIES
IEnumerable<File> Files { get; set; }
}
public class File
{
//Model PROPERTIES
}
public class FolderViewModel : INotifyPropertyChanged
{
//View Model PROPERTIES
IEnumerable<FileViewModel> Files { get; set; }
}
public class FileViewModel : INotifyPropertyChanged
{
//View Model PROPERTIES
public bool IsSelected { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.