1 回答

TA貢獻1808條經(jīng)驗 獲得超4個贊
您應該封裝翻譯及其操作。為此,只需引入一個類,例如TranslationService在所有相關視圖模型之間共享的類。為了省略臭單例,我將服務的實例添加到App.xaml資源中。
這個想法是翻譯列表的所有修改都發(fā)生在一個位置或類型中。與視圖的綁定源相同的類型。添加新翻譯時,視圖應調用ICommand視圖模型上的 a。該命令將AddTranslation調用TranslationService. 刪除也一樣。對翻譯集合的任何更改現(xiàn)在都將反映在整個應用程序中。
如果您還想捕獲實際翻譯的修改(例如重命名或編輯),則還TranslationService需要處理項目PropertyChanged的事件。 當項目屬性更改時,必須通過引發(fā)該屬性的事件來響應。這也需要實施這些項目。ObservableCollection
TranslationServicePropertyChangedObservableCollectionTranslationsINotifyPropertyChanged
App.xaml
共享TranslationService實例
<Application.Resources>
<TranslationService x:Key="TranslationService">
<TranslationService.DatabaseService>
<DatabaseService />
</TranslationService.DatabaseService>
</TranslationService>
</Application.Resources>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private void ListViewItem_PreviewMouseDown(objectsender,MouseButtonEventArgs e)
{
// Instantiate the view model and initialize DataContext from XAML instead.
// This method became redundant.
}
}
主窗口.xaml
<Window.DataContext>
<ModifyWordVM>
<ModifyWordVM.TranslationService>
<!-- Reference the shared instance -->
<StaticResource ResourceKey="TranslationService" />
</ModifyWordVM.TranslationService>
</ModifyWordVM>
</Window.DataContext>
修改WordVM.cs
public class ModifyWordVM: INotifyPropertyChanged
{
public ModifyWordVM()
{}
public AddTranslation(Translation translation) => this.translationService.AddTranslation(translation);
public RemoveTranslation(Translation translation) => this.translationService.RemoveTranslation(translation);
public TranslationService TranslationService {get; set;}
public ObservableCollection<TranslationVM> Translations => this.translationService.Translations;
}
翻譯服務.cs
public class TranslationService
{
public TranslationService()
{}
public AddTranslation(Translation translation)
{
// Add translations
}
public RemoveTranslation(Translation translation)
{
// Remove translations
}
private DatabaseService databaseService;
public DatabaseService DatabaseService
{
get => this.databaseService;
set
{
this.databaseService = value;
this.Translations = databaseService.getTranslations;
}
}
private ObservableCollection<TranslationVM> translations;
public ObservableCollection<TranslationVM> Translations
{
get => this.translations;
set
{
this.translations = value;
OnPropertyChanged("Translations");
}
}
}
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報