WPF not load a control - wpf

I write a very easy UserControl
here the Xaml code
<UserControl x:Name="Test1" x:Class="WpfAppXtesting.UserControl1"
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:WpfAppXtesting"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Loaded="Test1_Loaded">
<Grid x:Name="GridRoot" Background="Aqua">
<TextBlock x:Name="status" HorizontalAlignment="Left" Height="137" Margin="100,137,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="483" FontSize="48"/>
</Grid>
and here the code behind
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.GridRoot.DataContext = this;
}
private void UserControl1_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Connected":
status.Text = ((App)sender).Connected.ToString() ;
break;
}
}
private void Test1_Loaded(object sender, RoutedEventArgs e)
{
(Application.Current as App).PropertyChanged += UserControl1_PropertyChanged;
}
}
the problem is , when import this control in a Window in same project The design mode gets this error.
NullReferenceException: Object reference not set to an instance of an object.
if I run the project everything was good.
If I commented the line in Loaded method
the control was right shown in design mode.
Any Idea?
thanks

Do not assume that Application.Current is your application at design time. For example, when you are using Expression Blend, Current is Expression Blend. At design time, MainWindow is not your application's main window. Typically operations that cause a user/custome control to fail at design time include the following.
Casting Current to your custom subclass of App.
Casting MainWindow to your custom subclass of Window.
Here are two approaches to writing code for design time. The first approach is to write defensive code by checking the null condition. The second approach is to check whether design mode is active by calling the GetIsInDesignMode method. You can read about GetIsInDesignMode at here.
Solution 1:
private void Test1_Loaded(object sender, RoutedEventArgs e)
{
var app = Application.Current as App;
if( app != null)
{
app.PropertyChanged += UserControl1_PropertyChanged;
}
}
Solution 2 :
private void Test1_Loaded(object sender, RoutedEventArgs e)
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
// Design-mode specific functionality
(Application.Current as App).PropertyChanged += UserControl1_PropertyChanged;
}
}

Related

How to get all windows close when you select 'Close All Windows' on the app's taskbar icon?

So I've been doing research on this for quite a few weeks now, and haven't really come up with an answer on why this doesn't work properly... I've even researched JumpLists to see if this was what I was looking for, but also to no avail. This problem relates to when you attempt to select 'Close All Windows' by right clicking an app's icon on the task bar...
For example, here is an EXTREMELY small and simple WPF application I wrote to demonstrate the problem I am having. Here is the app's icon in the task bar with its choices on the context menu for it...
contextmenutoolbar
I am selecting the choice 'Close all windows', for reference (the bottom one, with the X to the left of it).
This is a WPF application and here is the code for App.xaml:
<Application x:Class="CloseAllWindows.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Application.Resources>
</Application.Resources>
</Application>
Here is App.xaml.cs, which launches the MainWindow. It also sets the application's MainWindow property to the MainWindow that is instantiated. It also sets ShutdownMode to be only when the main window is closed... I don't want the application to still run if the main window is closed and some secondary windows are left open.
using System.Windows;
namespace CloseAllWindows
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
ShutdownMode = ShutdownMode.OnMainWindowClose;
var mainWindow = new MainWindow();
Application.Current.MainWindow = mainWindow;
mainWindow.Show();
}
}
}
Here is the code for MainWindow.xaml:
<Window x:Class="CloseAllWindows.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:CloseAllWindows"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Content="NewWindow" Click="ButtonBase_OnClick"></Button>
</StackPanel>
</Window>
And here is the code behind for it... which launches a secondary window when I click a button. It is setting the parent window (Owner property) to the main window, like all the examples I've seen say it should be set, and then call Show() on it.
using System;
using System.ComponentModel;
using System.Windows;
namespace CloseAllWindows
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var childWindow = new ChildWindow {Owner = this};
childWindow.Show();
}
}
}
Here is the code for the child window, ChildWindow.xaml:
<Window x:Class="CloseAllWindows.ChildWindow"
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:CloseAllWindows"
mc:Ignorable="d"
Title="ChildWindow" Height="300" Width="300">
<Grid>
</Grid>
</Window>
And it's corresponding code behind, ChildWindow.xaml.cs:
using System;
using System.Windows;
namespace CloseAllWindows
{
/// <summary>
/// Interaction logic for ChildWindow.xaml
/// </summary>
public partial class ChildWindow : Window
{
public ChildWindow()
{
InitializeComponent();
}
}
}
As you can see, these classes do not do very much... it was the simplest example of code I could write that shows the problem I am having. So the issue is, if I select Close all windows from the task bar context menu, it never closes all the windows. Instead, it will close the one child window, and still leave the main window open. Interestingly, I hear the windows dialogue chime when I do this, almost like its getting interrupted by something, but I have no idea what.
It also appears to act very randomly... if I spawn 20 windows, it will sometimes close 6 of the windows, then all of them... sometimes it will close a few windows one by one, then close the rest... sometimes it will close all child windows and leave only the main window open. Needless to say, I am pretty baffled as to the behaviour since it doesn't seem to follow any noticeable pattern... any help greatly appreciated! And hopefully the example is good enough to explain what I am trying to get at....
Well you could add an event that will close every window the event is implanted in. try this example:
step 1: add a class to your project call it whatever you want, I called it CloseWindowListener, add this code to your class:
public static class CloseWindowListener
{
public static event EventHandler<EventArgs> ClosingWindows;
public static void CloseWindows()
{
var CWindows = ClosingWindows;
if (CWindows != null)
{
CWindows(null, EventArgs.Empty);
}
}
}
step 2: Add the event handler to the window you desire to close when it is called.
public partial class TestWindow1 : Window
{
public TestWindow1 ()
{
InitializeComponent();
CloseWindowListener.ClosingWindows += CloseWindowListener_ClosingWindows;
}
private void CloseWindowListener_ClosingWindows(object sender, EventArgs e)
{
this.Close();
}
}
step 3: simply call the event from your main window or where ever you want.
private void button_Click_1(object sender, RoutedEventArgs e)
{
CloseWindowListener.CloseWindows();
}

How to make a second project in the same solution for Windows Phone/Wpf/Windows type of solution

I have a Windows Phone project and my business demands to create another one with some slight changes in the front-end (XAML). How to create another project that is identical to the first one but only the XAML files are different? I don't use MVVM. What I tried is creating a new project and copy the XAML files from the first one, and then LINK all other CS files, but it became a mess with all these namespaces and stuff.. I have resource dicionaries and lots of dependencies in the code. Any ideas how to make such a project that shares the same code-behind files with some differences in Visual Studio?
XAML with a code behind are partial classes. You cannot have two partial classes referring to the same class in two different assemblies. Therefore I think you can't use common code behind for XAML from different projects.
The best approach is using a common view model for different views, but you don't use MVVM pattern.
Then you can use something like a proxy. The proxy is a common class in a separate assembly. It contains all logic and data.
You get or set any state from your code behind only by the proxy.
UPD: Example:
It's a common contract for each view (it's an interface from a common assembly):
public interface IMyWindow
{
Label HelloLabel { get; }
}
It's the first WPF project:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="First Application" Height="350" Width="525">
<StackPanel>
<Label x:Name="_helloLabel" Content ="Hello, I'm First Application!"></Label>
<Button Click="ButtonBase_OnClick" Height="100">Press me</Button>
</StackPanel>
</Window>
public partial class MainWindow : Window, IMyWindow
{
private readonly MyWindowProxy _proxy;
public MainWindow()
{
InitializeComponent();
_proxy = new MyWindowProxy(this);
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_proxy.OnButtonClick();
}
public Label HelloLabel
{
get { return _helloLabel; }
}
}
It's the second WPF project:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Second Application" Height="350" Width="525">
<StackPanel>
<Label x:Name="_helloLabel" Content ="Hello, I'm Second Application!"></Label>
<Button Click="ButtonBase_OnClick" Width ="50" Height="50">OK</Button>
</StackPanel>
</Window>
public partial class MainWindow : Window, IMyWindow
{
private readonly MyWindowProxy _proxy;
public MainWindow()
{
InitializeComponent();
_proxy = new MyWindowProxy(this);
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_proxy.OnButtonClick();
}
public Label HelloLabel
{
get { return _helloLabel; }
}
}
It's a proxy for each view (it's a class from a common assembly):
public class MyWindowProxy
{
private readonly IMyWindow _window;
public MyWindowProxy(IMyWindow window)
{
_window = window;
}
public void OnButtonClick()
{
_window.HelloLabel.Content = "Hello from common proxy!";
}
}
Once again, this is NOT the best way to build an application architecture. I highly recommend using MVVM pattern then the question of separating of business logic disappear by itself.

WPF, Displaying Emgu Image, using Binding

I am familiar with basic code to display an Emgu image in a WPF image box, when all the source code is in the MainWindow.xaml.cs code-behind.
However I am trying to place my Emgu-related code, including the "ProcessFrame" event / Queryframe snippet, into a separate class of static methods so that I can reuse them later. I am doing this because while I will want to be able to grab images from the same camera at a later stage, I also want the flexibility to display those images in a different image box. I am having trouble with this step.
If I could bind the Image box dynamically to a property in the static method (and also enable / disable that binding programmatically), I think that would solve my problem. However, there may be some other problem with the approach I am trying to take. Any code / xaml modifications greatly appreciated.
The following code works, but is unsatisfactory because it forces me to bundle ProcessFrame method into the MainWindow code:
XAML (working):
<Window x:Class="EmguWPF_Test.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>
<Image Height="215" HorizontalAlignment="Left" Margin="62,66,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="224" />
</Grid>
</Window>
MainWindow Code Snippet (working):
//using statements etc
public partial class MainWindow : Window
{
private Image<Bgr, Byte> image;
private Capture capture = null;
private void button1_Click(object sender, RoutedEventArgs e)
{
InitializeCameras();
timer = new DispatcherTimer();
timer.Tick+=new EventHandler(ProcessFrame);
timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
timer.Start();
}
private void InitializeCameras()
{
if (capture == null)
{
try
{
capture = new Capture(0);
}
catch // etc
}
}
private void ProcessFrame(object sender, EventArgs arg)
{
image = capture.QueryFrame();
image1.Source = BitmapSourceConvert.ToBitmapSource(image);
}
}
public static class BitmapSourceConvert
{
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
public static BitmapSource ToBitmapSource(IImage image)
{
using (System.Drawing.Bitmap source = image.Bitmap)
{
IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ptr,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ptr); //release the HBitmap
return bs;
}
}
}
The following code is where I am up to but need help:
XAML (same as before)
<Window x:Class="EmguWPF_Test.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>
<Image Height="215" HorizontalAlignment="Left" Margin="62,66,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="224" />
</Grid>
</Window>
ViewModel Snippet (yes - perhaps too ambitious to be experimenting with design patterns):
public ViewModel()
{
CaptureMethods.InitializeCameras();
timer = new DispatcherTimer();
timer.Tick += new EventHandler(CaptureMethods.ProcessFrame);
timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
timer.Start();
}
CaptureMethods class, not working as a separate class in the way I want it to. You will notice I am now defining the capture field in this class, not in the ViewModel class:
class CaptureMethods
{
private static Capture capture = null;
public static void InitializeCameras()
{
if (capture == null)
{
try
{
capture = new Capture(0);
}
catch // etc
}
}
public static void ProcessFrame(object sender, EventArgs arg)
{
image = capture.QueryFrame();
image1.Source = BitmapSourceConvert.ToBitmapSource(image); // this is my problem line
}
}
// BitmapSourceConvert class not repeated here to avoid duplication.
Thanks!
My suggestion is not to use the WPF Image Box, but the Emgu's ImageBox (Emgu.CV.UI.ImageBox). It is a more complete control and it is designed to use with the framework.
The only problem is that type of control only works with Windows Forms, but you can always create a WinForms User Control with a Emgu's Image Box and use it in WPF inside a WindowsFormsHost.
To expand a bit on celsoap7's answer here is what the resulting XAML might look like:
<Window x:Class="WPFEmguCV.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:emui="clr-namespace:Emgu.CV.UI;assembly=Emgu.CV.UI"
Title="MainWindow" Height="521" Width="1274">
<Grid>
<WindowsFormsHost>
<emui:ImageBox x:Name="CapturedImageBox" Width="409" Height="353" />
</WindowsFormsHost>
</Grid>
</Window>
I (and others) found that marshaling the images onto the UI thread takes too much CPU and so you are better off doing as celsoap7 suggests and put an EmguCV ImageBox inside a WPF WindowsFormsHost.
Sadly that may make the kind of MVVM binding you are asking about quite different from the structure you envisage.

focus visual not showing when navigating focus programically

Whenever I try to move focus programmatically the focus visual (the dotted rectangle) does not display.
What can be done to force this visual to display?
<Window x:Class="WpfApplication2.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" Loaded="OnLoaded">
<StackPanel>
<TextBlock x:Name="a" Focusable="True">A</TextBlock>
<TextBlock Focusable="True">B</TextBlock>
<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)
{
Keyboard.Focus(a);
}
private void OnClick(object sender, RoutedEventArgs e)
{
var request = new TraversalRequest(FocusNavigationDirection.Next);
var elementWithFocus = Keyboard.FocusedElement as UIElement;
if (elementWithFocus != null)
elementWithFocus.MoveFocus(request);
}
}
If you look (in reflector/ilspy) at the KeyboardNavigation's ShowFocusVisual you'll find that the framework will only show it if the last input was from the keyboard (or if an internal static property based on the KeyboardCues system parameter info is true). So I don't think there is a good way to do this short of using reflection to temporarily set that property or asynchronously focusing the element and forcing a keyboard action (maybe using the winforms SendKeys or keybd_event api) but I wouldn't recommend either.

Mapping TouchMove Events to MouseMove Events in WPF

I'm implementing a simple drag and drop feature in a WPF application. I want this application to run on both desktops with no touch support and also on tablets with only touch support.
Currently I have a MouseMove and TouchMove handler, both implementing the same logic (Starting the DoDragDrop()).
How can I route the input from touch to the mouse handler or visa versa to reduce redundant code? Further how would one route a simple tap to a click event?
I just done a quick test and one way to do this is to create a Global event handler.
Since TouchEventArgs and MouseButtonEventArgs derive from InputEventArgs, your global handler will just implement InputEventArgs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//private void Button_TouchMove(object sender, TouchEventArgs e)
//{
// TouchEventArgs derives from InputEventArgs
//}
// private void Button_MouseMove(object sender, MouseButtonEventArgs e)
//{
// MouseButtonEventArgs derives from InputEventArgs
//}
private void GlobalHandler(object sender, InputEventArgs e)
{
// This will fire for both TouchEventArgs and MouseButtonEventArgs
// If you need specific information from the event args you can just cast.
// e.g. var args = e as MouseButtonEventArgs;
}
}
Xaml:
<Window x:Class="WpfApplication3.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 >
<Button MouseMove="GlobalHandler" TouchMove="GlobalHandler"/>
</Grid>
</Window>
Hope this helps

Resources