![](/img/trans.png)
[英]Avalonia ReactiveUI RoutedViewHost not creating embedding appropriate view
[英]Show dialog from ViewModel in ReactiveUI Avalonia (MVVM)
我有Window
,繼承自ReactWindow
,並且它連接到它的Viewmodel
。
一切都按預期工作(綁定、點擊內容、點擊命令)。 所以它正在工作。 (代碼如下)
當想要顯示文件瀏覽器對話框時,API 需要一個Window
對象作為ShowAsync(window)
的參數,我在ViewModel
類中沒有該對象。
一個選擇是從窗口本身做所有事情,但這違背了 MVVM 的目的,所以我的另一個選擇是將視圖轉發到視圖模型,但這似乎也很奇怪。
我也嘗試過(如您在下面的代碼中看到的)向命令添加一個參數,以便視圖可以轉發它,但是當您在WhenActivated
中設置它時您無法提供參數,所以我有點卡在這里。
我該怎么辦 ?
這是視圖模型
public class BatchManagementViewModel : ViewModelBase
{
public string BrowseText => "Browse/Edit files...";
public ReactiveCommand<BatchManagementView, Unit> BrowseCommand { get; set; }
public BatchManagementViewModel()
{
BrowseCommand = ReactiveCommand.CreateFromTask( async () => ShowFileDialog(/*THE VIEW HERE ?*/));
}
async Task<string[]?> ShowFileDialog(BatchManagementView view)
{
// view is null here so it obviously crashes on ShowAsync
//but it's a param of the Command
var dialog = new OpenFileDialog();
dialog.AllowMultiple = true;
dialog.Title = DialogTitle;
dialog.Filters.AddRange(
new FileDialogFilter[]
{
new() {Name = "image files", Extensions = { ".png", ".jpg", ".jpeg", ".tiff" }}
}
);
return await dialog.ShowAsync(view);
}
}
視圖/窗口
public partial class BatchManagementView : ReactiveWindow<BatchManagementViewModel>
{
public BatchManagementView()
{
InitializeComponent();
this.WhenActivated(d =>
{
this.OneWayBind(ViewModel,
viewModel => viewModel.BrowseText,
view => view.BrowseButton.Content)
.DisposeWith(d);
this.OneWayBind(ViewModel,
viewModel => viewModel.BrowseCommand,
view => view.BrowseButton.Command)
.DisposeWith(d);
});
}
}
我應該在這里做什么? 我覺得我正在嘗試實現一些簡單的事情,但我在文檔中找不到響應式 / MVVM 的示例。
可以從應用程序的任何位置檢索主窗口:
var mainWindow = Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop ? desktop.MainWindow : null;
然后,如果您希望跟上 MVVM 模式,您可以將顯示對話框的這種實現移至視圖服務。
閱讀互動。 基本上,您所做的是在您的視圖模型中創建一個交互,其中包括對話框的輸入和輸出。 然后在窗口后面的代碼中注冊一個處理程序來處理打開對話框的交互。 見這里: https ://docs.avaloniaui.net/tutorials/music-store-app/opening-a-dialog
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.