为什么仅在设计时在 WPF UserControl 及其所有者 Window 中出现构建错误?
Why do I get a build error in a WPF UserControl and its owner Window only at design time?
我有一个 MainMenu
用户控件,我在我的 MainWindow
视图中使用它,它有一个 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 个错误,都是:
Unable to cast object of type 'System.Windows.Application' to type
'ApptEase.Client.App'
第一个出现在上面用户控件标记的 <shell:MainWindowViewModel />
行中。第二个出现在下面 MainWindow
标记摘录的 <shell:MainMenu Grid.Row="0" />
行中。
主窗口摘录:
<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
行,错误就会消失。然而,当我构建时,除了输出 window 中的 "successful build" 之外,我没有看到任何输出,并且应用程序启动正常,即 BaseViewModel
ctor 执行正常,无一例外。
如果我别无选择,只能接受错误信息是无害的,有没有办法抑制它们?我没有看到编译器指令在 XAML 标记中工作。
我不知道这只是一个 'catch-all' 还是一个合适的解决方案,但我已经通过将我的 BaseViewModel
ctor 更改为如下所示解决了我的问题:
protected BaseViewModel()
{
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
_app = (App)Application.Current;
}
}
似乎在设计模式下,Application.Current
不是App
类型。
我有一个 MainMenu
用户控件,我在我的 MainWindow
视图中使用它,它有一个 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 个错误,都是:
Unable to cast object of type 'System.Windows.Application' to type 'ApptEase.Client.App'
第一个出现在上面用户控件标记的 <shell:MainWindowViewModel />
行中。第二个出现在下面 MainWindow
标记摘录的 <shell:MainMenu Grid.Row="0" />
行中。
主窗口摘录:
<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
行,错误就会消失。然而,当我构建时,除了输出 window 中的 "successful build" 之外,我没有看到任何输出,并且应用程序启动正常,即 BaseViewModel
ctor 执行正常,无一例外。
如果我别无选择,只能接受错误信息是无害的,有没有办法抑制它们?我没有看到编译器指令在 XAML 标记中工作。
我不知道这只是一个 'catch-all' 还是一个合适的解决方案,但我已经通过将我的 BaseViewModel
ctor 更改为如下所示解决了我的问题:
protected BaseViewModel()
{
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
_app = (App)Application.Current;
}
}
似乎在设计模式下,Application.Current
不是App
类型。