Browser has not initialized in tabitem with ChromiumWebBrowser WPF - c#

I have problem with control Cefsharp ChromiumWebBrowser in WPF. Project contain UserControl and Tabitem which is inside UserControl. When program is running and i move to tabitem control i have exception thrown
An exception of type 'System.Exception' occurred in CefSharp.dll but
was not handled in user code IBrowser instance is null. Browser has
likely not finished initializing or is in the process of disposing.
XAML
<UserControl x:Class="QuoteHubWPF.Controls.ChromeWebBrowser"
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"
xmlns:local="clr-namespace:QuoteHubWPF.Controls"
xmlns:cefSharp="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
xmlns:ge="clr-namespace:SourceChord.ResponsiveGrid;assembly=ResponsiveGrid.Wpf"
mc:Ignorable="d" ClipToBounds="True">
<cefSharp:ChromiumWebBrowser Name="chromiumWebBrowser" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" RenderTransformOrigin="0.5,0.5" Height="360" ClipToBounds="True" Loaded="ChromiumCKEditor_Loaded" IsBrowserInitializedChanged="browser_IsBrowserInitializedChanged" FrameLoadEnd="chromiumWebBrowser_FrameLoadEnd"/>
.cs
public partial class ChromeWebBrowser : UserControl
{
public ChromeWebBrowser()
{
InitializeComponent();
chromiumWebBrowser.Address = "html";
}
public string GetHTML()
{
var htmlFromPage = chromiumWebBrowser.EvaluateScriptAsync("getDataFromTheEditor", 10000);
here exist exception
var response = htmlFromPage.Result;
var result = response.Success ? (response.Result ?? "null").ToString() : response.Message;
return result;
}
private void browser_IsBrowserInitializedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
some code to run script
}
}
Any solution to fix this problem ? Its occurs when run tabitem control.
Update with explained problem
Thank for quickly answer #amaitland. GetHtml is calling in other viewmodel. So how i can initialize once again without error with over process ?
NewJobViewModel
public void GetHTMLFromView()
{
if (View != null)
{
var njView = View as NewJobUC;
var contentJobDescription = njView.JobDescriptionCKEditor.GetHTML();
NewJobUC.xaml
<TabItem ...some code ...
<local:ChromeWebBrowser x:Name="JobScopeCKEditor" CKEContent="{Binding NewJob.JobScope}" HorizontalAlignment="Stretch" Width="{Binding ElementName=canv, Path=ActualWidth}" />
</TabItem>

Related

How can i change a Page in my wpf Main Window?

i want to switch pages that are hosted on my main window. The first page (at App Start) is beeing shown correctly. But if i want to change the page it won´t happen. I even don´t get an error. It just shows the first page! Here´s my code:
The constructor of MainWindow:
public MainWindow(SchraubUser _schraubUser, string page = "")
{
schraubUser = _schraubUser;
db = new AccessDatabase(schraubUser._DATABASE_PATH);
ViewModel.ViewModel wzViewModel = new ViewModel.ViewModel(schraubUser, db);
InitializeComponent();
if (page == "")
{
Main.Content = new View.Werkzeug_Window(wzViewModel);
}
else
{
Main.Content = new View.Freigaben(wzViewModel);
}
}
At Application start the optional variable is "" so the mainwindow will display View.Werkzeug_Window (works correctly).
Here`s the code for changing the page:
private void Button_Freigaben_Click(object sender, RoutedEventArgs e)
{
mainWindow = new MainWindow(sb_vm.schraubUser, "Freigabe");
}
But it will still show the first page. Why is that?
XAML of MainWindow:
<Window x:Class="SchrauberDB.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SchrauberDB"
mc:Ignorable="d"
Title="MainWindow" Height="750" Width="1100"
WindowState="Maximized">
<Grid x:Name="mainGrid">
<Frame x:Name="Main" />
</Grid>
</Window>
This is so embarrassing...
private void Button_Freigaben_Click(object sender, RoutedEventArgs e)
{
mainWindow = new MainWindow(sb_vm.schraubUser, "Freigabe");
mainWindow.Show();
}

VtkActor is not displayed on WPF project

I am trying to load a RenderWindowControl from vtk libraries on my WPF project using ActiViz.NET and Visual Studio 2013. The library works fine since I did a new project just to practice on it but when I try to integrate it into my work, the actor is not shown. This is my code:
MainWindow.xaml:
<Window x:Class="myProject.Views.MainWindow"
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"
xmlns:VtkTab="clr-namespace:myProject.Views.UITabs.VtkTab"
x:Name="Mainwindow"
MinHeight="600"
MinWidth="800"
Title="{Binding Title}"
Height="720"
Width="1280"
Icon="{StaticResource ApplicationIcon}"
Loaded="OnLoaded"
DataContext="{Binding Main, Source={StaticResource ViewModelLocator}}"
Style="{StaticResource WindowStyle}"
mc:Ignorable="d">
<DockPanel>
<TabControl>
....
....
<VtkTab:VtkTabView />
....
....
</TabControl>
</DockPanel>
</Window>
VtkTabView.xaml:
<UserControl x:Class="myProject.Views.UITabs.VtkTab.VtkTabView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vtk="clr-namespace:Kitware.VTK;assembly=Kitware.VTK"
Height="480" Width="640">
<WindowsFormsHost Name="Wfh">
<vtk:RenderWindowControl x:Name="RenderControl" />
</WindowsFormsHost>
</UserControl>
VtkTabView.xaml.cs:
public partial class UITabView
{
protected static Random _random = new Random();
vtkActor actor = vtkActor.New();
public VtkTabView()
{
InitializeComponent();
var sphere = vtkSphereSource.New();
sphere.SetThetaResolution(8);
sphere.SetPhiResolution(16);
var shrink = vtkShrinkPolyData.New();
shrink.SetInputConnection(sphere.GetOutputPort());
shrink.SetShrinkFactor(0.9);
var move = vtkTransform.New();
move.Translate(_random.NextDouble(), _random.NextDouble(), _random.NextDouble());
var moveFilter = vtkTransformPolyDataFilter.New();
moveFilter.SetTransform(move);
moveFilter.SetInputConnection(shrink.GetOutputPort());
var mapper = vtkPolyDataMapper.New();
mapper.SetInputConnection(moveFilter.GetOutputPort());
// The actor links the data pipeline to the rendering subsystem
actor.SetMapper(mapper);
actor.GetProperty().SetColor(1, 0, 0);
RenderControl.Load += RenderWindowControlOnLoad;
}
void RenderWindowControlOnLoad(object sender, EventArgs e)
{
var renderer = RenderControl.RenderWindow.GetRenderers().GetFirstRenderer();
renderer.AddActor(actor);
renderer.SetBackground(0, 1, 0);
renderer.Render();
}
}
As you can see, in the method RenderWindowControlOnLoad (VtkTabView.xaml.cs) I take the actor (a Sphere) and I add it to the render declared into the WPF but it is not displayed. I tried to change the background color and call to render just in case but it's still not working :(
Call
RenderControl.RenderWindow.Render();
instead of
renderer.Render();

How to show programmatically FocusVisualStyle?

Afters attemps I could tell that the FocusVisualStyle is only activated by the keyboard (tab and arrows keys).
Try to make the FocusVisualStyle to be applied after the component is loaded, it is impossible to do, There is an easy way to get around this problem?
I found this:
- focus visual not showing when navigating focus programically
- How do WPF buttons decide to show FocusVisualStyle?
- http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/99856840-f8ef-4547-9150-c4c46ec2f3df
But none shows a definite solution (without overwriting the component), and I could not write, can someone help?
I am not pretty sure I understand your issue, but I tried the example in one of the links and I was able to move focus to next component from code behind exactly as you would do using keyboard. Here is the code.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplication1" Loaded="OnLoaded"
>
<StackPanel Margin="10">
<TextBox Margin="10" x:Name="a" >A</TextBox>
<TextBox Margin="10" x:Name="b" >B</TextBox>
<Button Focusable="False" Click="OnClick">Move Focus</Button>
</StackPanel>
</Window>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void OnLoaded(object sender, RoutedEventArgs e) {
a.Focus();
}
private void OnClick(object sender, RoutedEventArgs e) {
var request = new TraversalRequest(FocusNavigationDirection.Next);
var elementWithFocus = FocusManager.GetFocusedElement(FocusTest) as UIElement;
if (elementWithFocus != null)
elementWithFocus.MoveFocus(request);
}
}

KinectColorViewer SDK 1.7

I'm trying to make KinectColorViewer to work with SDK 1.7 but without success. I can display video picture only if I manually copy pixels from camera to Image element.
I have the following XAML:
<Page
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"
xmlns:k="http://schemas.microsoft.com/kinect/2013"
xmlns:WpfViewers="clr-namespace:Microsoft.Samples.Kinect.WpfViewers;assembly=Microsoft.Samples.Kinect.WpfViewers" x:Class="KinectD.Camera"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="500"
Title="Camera">
<Grid>
<k:KinectUserViewer k:KinectRegion.KinectRegion="{Binding ElementName=kinectRegion}" Height="100" HorizontalAlignment="Center" VerticalAlignment="Top" />
<k:KinectSensorChooserUI HorizontalAlignment="Center" VerticalAlignment="Top" x:Name="sensorChooserUi" />
<k:KinectRegion x:Name="kinectRegion">
<Grid>
<k:KinectCircleButton Label="Menu" HorizontalAlignment="Right" Height="200" VerticalAlignment="Top" Click="MenuButtonOnClick" >
<StackPanel>
<Image Source="Images/smile.png" Height="30"/>
</StackPanel>
</k:KinectCircleButton>
</Grid>
</k:KinectRegion>
<WpfViewers:KinectColorViewer HorizontalAlignment="Left" Height="240" Margin="10,10,0,0" VerticalAlignment="Top" Width="320" Kinect="{Binding ElementName=sensorChooserUi, Mode=OneWay, Path=Kinect}"/>
</Grid>
And XAML.CS:
public partial class Camera : Page
{
#region "Kinect"
private KinectSensorChooser sensorChooser;
#endregion
public Camera()
{
this.InitializeComponent();
// initialize the sensor chooser and UI
this.sensorChooser = new KinectSensorChooser();
//Assign the sensor chooser with the sensor chooser from the mainwindow.
//We are reusing the sensorchoosing declared in the first window that can in contact with kinect
this.sensorChooser = Generics.GlobalKinectSensorChooser;
//subscribe to the sensorChooserOnKinectChanged event
this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;
//Assign Kinect Sensorchooser to the sensorchooser we got from our static class
this.sensorChooserUi.KinectSensorChooser = sensorChooser;
// Bind the sensor chooser's current sensor to the KinectRegion
var regionSensorBinding = new Binding("Kinect") { Source = this.sensorChooser };
BindingOperations.SetBinding(this.kinectRegion, KinectRegion.KinectSensorProperty, regionSensorBinding);
}
private void SensorChooserOnKinectChanged(object sender, KinectChangedEventArgs args)
{
bool error = false;
if (args.OldSensor != null)
{
try
{
args.OldSensor.DepthStream.Range = DepthRange.Default;
args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false;
args.OldSensor.DepthStream.Disable();
args.OldSensor.SkeletonStream.Disable();
args.OldSensor.ColorStream.Disable();
}
catch (InvalidOperationException)
{
// KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
// E.g.: sensor might be abruptly unplugged.
error = true;
}
}
if (args.NewSensor != null)
{
try
{
args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
args.NewSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
args.NewSensor.SkeletonStream.Enable();
}
catch (InvalidOperationException)
{
error = true;
// KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
// E.g.: sensor might be abruptly unplugged.
}
}
if (!error)
kinectRegion.KinectSensor = args.NewSensor;
}
private void MenuButtonOnClick(object sender, RoutedEventArgs e)
{
//Unsubscribe to the sensorchooser's event SensorChooseronkinectChanged
this.sensorChooser.KinectChanged -= SensorChooserOnKinectChanged;
(Application.Current.MainWindow.FindName("_mainFrame") as Frame).Source = new Uri("MainMenu.xaml", UriKind.Relative);
}
}
In tutorial I was following (http://channel9.msdn.com/Series/KinectQuickstart/Camera-Fundamentals) instructor just drops KinectColorViewer to a screen, sets path and it's working.
The KinectColorViewer available in the KinectWpfViewers assembly is used in the "Kinect Explorer" example, and that is the best place to see how it is used and behaves. From this example you will find that the proper way to initialize the viewer in the XAML and the bindings that are necessary.
From the code you posted, you appear to binding the Kinect itself (a reference to the hardware) to the KinectColorViewer, which is not what it is expecting. You need to be setting a reference to a KinectSensorManager class, which is part of the KinectWpfViewers assembly.
Here is a simplified XAML with a KinectColorViewer
<Window x:Class="Microsoft.Samples.Kinect.KinectExplorer.KinectWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Microsoft.Samples.Kinect.KinectExplorer"
xmlns:kt="clr-namespace:Microsoft.Samples.Kinect.WpfViewers;assembly=Microsoft.Samples.Kinect.WpfViewers"
Title="Kinect Explorer" Width="812" Height="768">
<Grid>
<kt:KinectColorViewer x:Name="ColorViewer" KinectSensorManager="{Binding KinectSensorManager}" CollectFrameRate="True" RetainImageOnSensorChange="True" />
</Grid>
</Window>
Then you XAML.CS constructor will look something similar to:
public KinectWindow()
{
this.viewModel = new KinectWindowViewModel();
// The KinectSensorManager class is a wrapper for a KinectSensor that adds
// state logic and property change/binding/etc support, and is the data model
// for KinectDiagnosticViewer.
this.viewModel.KinectSensorManager = new KinectSensorManager();
Binding sensorBinding = new Binding("KinectSensor");
sensorBinding.Source = this;
BindingOperations.SetBinding(this.viewModel.KinectSensorManager, KinectSensorManager.KinectSensorProperty, sensorBinding);
// Attempt to turn on Skeleton Tracking for each Kinect Sensor
this.viewModel.KinectSensorManager.SkeletonStreamEnabled = true;
this.DataContext = this.viewModel;
InitializeComponent();
}
Review the "Kinect Explorer" example for complete details.
I had the same problem with using KinectSensorManager. It turns out you need to call to Microsoft.Samples.Kinect.Wpf.Viewers and not just the kinect.dll, kinect.toolkit.dll, and kinect.controls.dll.
However, when I implemented KinectSensorManager, then the KinectUI and SensorChooser stopped working on my xaml interface.

Setting control to be content of several controls

I have a control which i'm putting in dialog as a content. Due to relization of this dialog i have to create it every time when i need it(Show/Hide won't do the trick). I want my control to remember field content beetween calls. While i can apply viewmodel to achieve this i prefer just keep control as a field and assing it as content of dialog every time i need it. But i run into following error:
"Specified element is already the logical child of another element. Disconnect it first."
I tried to assing null to dialog window's content before closing it, but it doesn't solve the problem. Is there anything i can do?
Setting window.Content = null works fine for me. Following is the code I used:
public partial class MainWindow : Window
{
TextBlock textBlock = new TextBlock();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TestWindow testWindow = new TestWindow();
testWindow.Content = textBlock;
testWindow.Closing += HandleTestWindowClosing;
testWindow.Show();
}
void HandleTestWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
var testWindow = sender as TestWindow;
if(testWindow!=null)
{
testWindow.Content = null;
testWindow.Closing -= HandleTestWindowClosing;
}
}
}
Check out the following working example. It isn't exactly your scenario, but pretty close. The key is setting the 'Child' property to null. It moves the TextBox from the top border to the bottom.
<Window x:Class="SO.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Grid.Row="0" Click="Move_Click">Move</Button>
<Border x:Name="topBorder" Grid.Row="1">
<TextBlock x:Name="ctrl">Some Text Block</TextBlock>
</Border>
<Border x:Name="bottomBorder" Grid.Row="2"/>
</Grid>
</Window>
and the code behind:
using System.Windows;
namespace SO
{
public partial class MainWindow :Window
{
public MainWindow( )
{
InitializeComponent( );
}
private void Move_Click( object sender, RoutedEventArgs e )
{
this.topBorder.Child = null;
this.bottomBorder.Child = this.ctrl;
}
}
}

Categories