[英]Error while building WPF project with Web Browser control
在我的應用程序中,我有一個使用WebBrowser
控件的UserControl
。
以下是UserControl
的代碼:
<UserControl x:Class="tool.ucMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="354" d:DesignWidth="440">
<Grid>
<DockPanel>
<WebBrowser Name="wbMap" DockPanel.Dock="Left" MinWidth="300"></WebBrowser>
<DataGrid Name="grdSignals" DockPanel.Dock="Right" ItemsSource="{Binding}" AutoGenerateColumns="False">
</DataGrid>
</DockPanel>
</Grid>
我使用這個UserControl
在另一個UserControl
具有TabControl
。 這是另一個UserControl
的代碼:
<Grid>
<TabControl>
<TabItem Name="tabMain" Header="Main">
<uc:ucMain />
</TabItem>
<TabItem Name="tabDataExplorer" Header="Data Explorer"/>
</TabControl>
</Grid>
ucMain是第一個UserControl
。 當我清理項目時,我可以看到第一個用戶控件。 但是當我構建/運行它時,它消失了,並且收到如下圖所示的錯誤。 即使在設計視圖中,我也會收到此錯誤。
我通過創建一個包含WebBrowser的UserControl來重復此行為,並將其命名為BrowserContainer。 然后,我創建了另一個名為BrowserBrowserContainer的UserControl,並向其中添加了我的第一個UserControl。 之后,我將BrowserBrowserContainer UserControl添加到我的測試項目的MainWindow.xaml文件中。
當給WebBrowser提供一個名稱(例如“ Browser”),然后將以下代碼添加到BrowserContainer的構造函數中時,我得到的行為與您描述的完全相同。
public BrowserContainer()
{
InitializeComponent();
Browser.Source = new Uri("c:\\thisfiledoesntexist");
}
自然,解決方案是不設置Source或將其設置為在設計時有效的東西。 無論您是否處於設計模式下,都會調用無參數構造函數。
如果嘗試導航到本地文件,則應始終在Uri路徑的前面附加file:///
。
編輯
我剛剛進行了測試,可以在主窗口的設計器視圖中看到此錯誤。 我可以看到Visual Studio試圖觸發UserControl的Loaded事件。 AppDomain.CurrentDomain.BaseDirectory以某種方式返回Visual Studio路徑。
跳過此錯誤的最佳方法可能是使用DesignerProperties.GetIsInDesignMode()
例如,您可以執行以下操作以在設計器視圖中跳過此錯誤。
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
if (DesignerProperties.GetIsInDesignMode(this)) return;
String appdir = System.IO.Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
String mapPath = System.IO.Path.Combine(appdir, "MAP.html");
ResultWebBrowser.Navigate(new Uri("file:///" + mapPath));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.