[英]Why do I get a build error in a WPF UserControl and its owner Window only at design time?
我在MainWindow
視圖中使用了MainMenu
用戶控件,該控件具有MainWindowViewModel
。 MainMenu
標記開始像:
<UserControl x:Class="ApptEase.Client.Shell.Controls.MainMenu"
....
d:DesignHeight="25">
<UserControl.DataContext>
<shell:MainWindowViewModel />
</UserControl.DataContext>
<Menu Height="25" VerticalAlignment="Top">
<MenuItem Header="_File">
在設計方式下,我的錯誤列表中出現2個錯誤,它們都是:
無法將類型為“ System.Windows.Application”的對象轉換為類型為“ ApptEase.Client.App”的對象
第一次發生在上述用戶控件標記中的<shell:MainWindowViewModel />
行中。 第二個發生在下面MainWindow
標記摘錄的<shell:MainMenu Grid.Row="0" />
行中。
MainWindow摘錄:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<shell:MainMenu Grid.Row="0" />
<ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" />
</Grid>
我的MainWindowViewModel
繼承自BaseViewModel
:
public abstract class BaseViewModel : BindableBase
{
protected BaseViewModel()
{
AppState = ((App)Application.Current).AppState;
}
...
}
如果我注釋掉((App)Application.Current).AppState
行,則錯誤消失了。 但是,在構建時,除了在輸出窗口中顯示“成功構建”外,我看不到任何輸出,並且該應用程序可以正常啟動,即BaseViewModel
ctor可以正常執行。
如果我別無選擇,只能接受錯誤消息是無害的,有什么辦法可以消除它們? 我看不到在XAML標記中起作用的編譯器指令。
我不知道這是“包羅萬象”還是適當的解決方案,但我通過將BaseViewModel
ctor更改為以下形式解決了我的問題:
protected BaseViewModel()
{
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
_app = (App)Application.Current;
}
}
在設計模式下, Application.Current
似乎不是App
類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.