Question

I am using CefSharp in my WPF project. I'm adding the CefSharp.Wpf.WebView class to my MainWindow.xaml like so:

_webView = new WebView(url, _settings);

My XAML layout looks like this:

<Window x:Class="WPFContainer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test Project" Height="400" Width="930" Initialized="OnWindowInit" StateChanged="OnWindowStateChanged" Closing="OnWindowClose">
  <DockPanel Name="MainDockPanel" Height="400" Width="930">
    <Grid VerticalAlignment="Top" HorizontalAlignment="Left" ShowGridLines="True" Name="mainGrid" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="col1" Width="600" />
            <ColumnDefinition Name="col2" Width="330"/>
        </Grid.ColumnDefinitions>
    </Grid>
  </DockPanel>
</Window>

If I remove the Grid and add the webView to the DockPanel directly, it shows up just fine. But if I try to add the webView to col1 in the Grid, it doesn't display. It will display in the grid column if I specify a Width/Height, but HorizontalAlignment.Stretch doesnt work and I need 100% width and height!

My code for adding the webView to the Grid which doesn't work:

mainGrid.Children.Add(_webView);
Grid.SetColumn(_webView, 0);
Was it helpful?

Solution

The problem is that the Children property is populated in InitializeComponent. If you are adding children to the grid after it has been initialize, there is no property changed event for adding to the Children collection, as it is not an ObservableCollection. If you were to create a new collection I believe it would work programmatically, but that can be avoided by defining your webview in xaml (provided it has a paramaterless constructor). Then OnLoaded you can inject url and settings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top