簡體   English   中英

從資源加載任務欄圖標並使用 Prism 注入視圖 model

[英]Loading a Taskbar Icon from resources and using Prism to inject view model

背景

我正在嘗試編寫一個主要存在於系統托盤上的應用程序,它將來有一個 window 所以右鍵單擊它打開 window 的圖標。

編碼

我目前沒有在 Prism 啟動時定義 shell,即:

protected override Window CreateShell()
{
    return null;
}

通知圖標(使用Hardcodet.NotifyIcon是否有任何區別?)在資源字典中定義,因為我沒有啟動視圖xaml 以將圖標添加到:

<!-- the application's NotifyIcon - started from App.xaml.cs. Declares its own view model. -->
    <tb:TaskbarIcon x:Key="NotifyIcon"
                    IconSource="{Binding UserStatus, Converter={StaticResource UserStatusToImageSourceConverter}}"
                    ToolTipText="Double-click for window, right-click for menu"
                    DoubleClickCommand="{Binding ShowWindowCommand}"
                    ContextMenu="{StaticResource SysTrayMenu}">

         <!--self-assign a data context (could also be done programmatically)--> 
        <tb:TaskbarIcon.DataContext>
            <viewModels:NotifyIconViewModel />
        </tb:TaskbarIcon.DataContext>
    </tb:TaskbarIcon>

視圖 model,正如您在該片段的后面部分看到的那樣,采用NotifyIconViewModel ,它有一個構造函數參數,因此我可以使用IEventAggregator在視圖的不同部分之間進行通信(就像當您顯示的上下文菜單中的視圖只需單擊托盤圖標)。

視圖 model 的簽名如下所示:

public NotifyIconViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator = eventAggregator;
    ...
}

服務已注冊:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    ...
    containerRegistry.Register<NotifyIconViewModel>();
}

而通知圖標本身是在OnInitialized方法中實例化的:

protected override void OnInitialized()
{
    base.OnInitialized();
    notifyIcon = (TaskbarIcon)FindResource("NotifyIcon");
}

問題

但是,啟動時拋出的異常是沒有為視圖 model 找到默認構造函數(正確,沒有)。 但我的閱讀是棱鏡架構應該能夠在需要時注入視圖 model (及其部門)?

XamlParseException

我只能假設我錯誤地初始化了通知圖標,並且 FindResource 不會導致觸發 prism 庫構造函數注入/DI 部分,但是執行此行為的正確方法是什么?

如果您使用容器構造(也稱為解析)object,則會注入依賴項。

This happens when a normal Prism application resolves the shell, which (by using the ViewModelLocator ) resolves the shell's view model which resolves alle the dependencies of the shell's view model and the dependencies of those dependencies and so on.

如果您使用容器(即直接在 xaml 中構造對象),它不會為您解決任何依賴關系。

您可以創建圖標並使用容器來解析NotifyIconViewModel並將其設置為DataContext

protected override void OnInitialized()
{
    base.OnInitialized();
    notifyIcon = (TaskbarIcon)FindResource("NotifyIcon");
    notifyIcon.DataContext = Container.Resolve<NotifyIconViewModel>();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM