WPF: Navigation Service Object Instance Error - c#

I am new to WPF and have attempted to look and try different solutions:
I need to navigate to another page: From Page called MainFrame to Page1.
Error messages:
WPF does not containt a definition for navigation service.
Or
Object not set to instance of Object.
I tried this:
private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
{
navService = NavigationService.GetNavigationService(this);
navService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
}
Then I tried this, thinkinig something needs to instantiate on page load:
NavigationService navService;
public MainFrame()
{
InitializeComponent();
}
void MainFrame_Loaded(object sender, RoutedEventArgs e)
{
navService = NavigationService.GetNavigationService(this);
}
private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
{
navService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
}

Use NavigationService instance in Page. Read MSDN article regarding Navigation
private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
{
this.NavigationService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
}

It should be pretty simple. The navigation happens in the NavigationWindow within Pages see example below:
First of all your main window should be inherited from a NavigationWindow class:
public partial class MainWindow : NavigationWindow
{
public MainWindow()
{
InitializeComponent();
}
}
then the xaml must have a NavigationWindow root element:
<NavigationWindow x:Class="NavigationApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window" Height="300" Width="300" Source="MainPage.xaml">
</NavigationWindow>
This root element cannot contain any UI elements, as they are placed in pages. The root element contains a starting page attribute MainPage.xaml
<Page x:Class="NavigationApp.MainPage"
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="300" d:DesignWidth="300"
Title="MainPage">
<Grid>
<Frame Source="Page2.xaml"/>
</Grid>
</Page>
In my case it contains a frame to a Page2.xaml which has only one button.
<Page x:Class="NavigationApp.Page2"
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="300" d:DesignWidth="300"
Title="Page2">
<Grid>
<Button Content="Navigate to page 1" HorizontalAlignment="Left" Margin="109,143,0,0" VerticalAlignment="Top" Width="128" Click="Button_Click"/>
</Grid>
</Page>
By clicking on that button it navigate to another page:
private void Button_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("Page1.xaml", UriKind.Relative);
NavigationService.Navigate(uri);
}

Related

Navigating with "Enter" focuses Button on other page

I have one "login page" and one "content page". The login page consists of a PasswordBox and a Button. When the button is clicked or the Enter-key is pressed in the PasswordBox, I want the program to navigate to the next page. Navigating with the button works fine, but when the page is changed due to the pressed enter key, the Button on the next page is focused. How can I disable/avoid this behaviour?
"Focused" button:
MainPage.xaml
<Page
x:Class="TabNavigation.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TabNavigation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<StackPanel>
<PasswordBox x:Name="textBox" KeyDown="HandleTextBox_KeyDown"/>
<Button x:Name="loginButton" Content="Einloggen" Click="HandleLoginButton_Click"/>
</StackPanel>
</Grid>
</Page>
MainPage.xaml.cs
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace TabNavigation {
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
}
private void HandleTextBox_KeyDown(object sender, KeyRoutedEventArgs e) {
if(e.Key == Windows.System.VirtualKey.Enter) {
this.Frame.Navigate(typeof(ContentPage));
}
}
private void HandleLoginButton_Click(object sender, RoutedEventArgs e) {
this.Frame.Navigate(typeof(ContentPage));
}
}
}
ContentPage.xaml
<Page
x:Class="TabNavigation.ContentPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TabNavigation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<StackPanel>
<Button>Test</Button>
</StackPanel>
</Grid>
</Page>
You can cancel the focus in GettingFocus:
<Button GettingFocus="Button_GettingFocus">Test</Button>
private void Button_GettingFocus(UIElement sender, GettingFocusEventArgs args)
{
args.Cancel = true;
}
Old answer:
You have few options:
Disable focus on button with IsTabStop=false
Change TabIndex to larger integer than other elements.
Set focus from your code to something else: otherControl.Focus(FocusState.Programmatic);

Is there a way to change the size and style of a host window from a navigationpage? (WPF)

I have a host window that has a page as follows:
<Window x:Class="myAPP.filesXAML.WinModel"
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:myApp.filesXAML"
mc:Ignorable="d"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize"
WindowStyle="None"
Title="myAPP" Height="562" Width="1000">
<Grid>
<Frame NavigationUIVisibility="Hidden" Source="/filesXAML/Login.xaml" Background ="White"/>
</Grid>
</Window>
Then in the code in C# I call another page as follows:
NavigationService.Navigate(new Uri("filesXAML/UserPage.xaml", UriKind.Relative));
At this point I want to change the size and style of the host window.
Is there a way to do it?
Any suggestions or comments are welcome.
You can use the following code to change the size of MainWindow in Page
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Application.Current.Windows[0].Width = 100;
Application.Current.Windows[0].Height = 100;
}
}

MainWindow gets closed when closing ChildWindow

I am developing a wpf application for the surface pro in tablet mode. I am coding on a different computer and there everything works fine. When testing the application on the surface pro something weird happens:
During the application a second window gets opened, in order to modify some settings. This window includes a button in order to close the window (see code below). When this button is clicked on the surface pro the whole application gets closed (including the main window). On the computer where I am writing the code this never happens, so in my opinion the problem lies with the hardware.
Thank you for your help!
Edit 21/03/2018
So as discussed in the comments I have tried several things and the problem remains. I have now deleted most of the application code such that only the essential feature remain and the problem still hasn't disappeared. I will post the code below:
App.xaml
<Application x:Class="TestNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestNamespace"
Startup="ApplicationStartup">
<Application.Resources>
<Style TargetType="{x:Type Window}">
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
</Application.Resources>
</Application>
App.xaml.cs
public partial class App : Application
{
public MainWindow window = new MainWindow();
public Monitoring monitoring;
private void ApplicationStartup(object sender, StartupEventArgs e)
{
window.Show();
monitoring = new Monitoring();
window.Content = monitoring.gui;
this.DispatcherUnhandledException += App_DispatcherUnhandledException;
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
System.Diagnostics.Debug.WriteLine("App1: There has been an unhandled exception");
throw new NotImplementedException();
}
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
System.Diagnostics.Debug.WriteLine("App2: There has been an unhandled exception");
throw new NotImplementedException();
}
}
GUI.xaml
<UserControl x:Class="TestNamespace.GUI"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:oxy="http://oxyplot.org/wpf"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:mi="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:local="clr-namespace:TestNamespace">
<Grid Background="Black">
<Button HorizontalAlignment="Center" VerticalAlignment="Center"
Width="300" Height="300"
Content="NewWindow" Click="SettingsButton_Click"/>
</Grid>
</UserControl>
GUI.xaml.cs
public partial class GUI : UserControl
{
private Monitoring monitoring;
public GUI(Monitoring monitoring)
{
this.monitoring = monitoring;
InitializeComponent();
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
System.Diagnostics.Debug.WriteLine(" GUI: There has been an unhandled exception");
throw new NotImplementedException();
}
private void SettingsButton_Click(object sender, RoutedEventArgs e)
{
monitoring.settingsWindow = new testWindow();
monitoring.settingsWindow.Show();
}
}
Monitoring.cs
public class Monitoring
{
private App currentApp = (App)Application.Current;
public GUI gui;
public Window settingsWindow;
public Monitoring()
{
gui = new GUI(this);
}
}
TestWindow.xaml
<Window x:Class="TestNamespace.testWindow"
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:TestNamespace"
mc:Ignorable="d"
Title="testWindow"
ResizeMode="NoResize" WindowState="Maximized" WindowStyle="None">
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="245,200,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>
</Window>
TestWindow.xaml.cs
public partial class testWindow : Window
{
public testWindow()
{
InitializeComponent();
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
System.Diagnostics.Debug.WriteLine("TestWindow: There has been an unhandled exception");
throw new NotImplementedException();
}
private void button_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
this.Close();
}
}
MainWindow.xaml
<Window x:Class="TestNamespace.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:local="clr-namespace:TestNamespace"
mc:Ignorable="d"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowState="Maximized" WindowStyle="None">
<Grid Background="White">
<TextBox x:Name="textBox" HorizontalAlignment="Center" Height="47" TextWrapping="Wrap" Text="LOADING..." VerticalAlignment="Center" Width="198" FontWeight="Bold" FontSize="36" BorderBrush="{x:Null}" />
</Grid>
</Window>
MainWindow.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
This is the complete code for the Minimal, Complete, and Verifiable example. This code still produces the error on the tablet. Thank you for your help!
I finally managed to solve the problem! Instead of creating and showing a new window, I created a new UserControl (TestWindow) and changed the content of the mainWindow. Upon closing the TestWindow, the normal GUI is loaded as Content of the MainWindow and the TestWindow is set to null.
It might not be the best solution, but it works.
EDIT 1
A few weeks later I stumbled upon the same problem once again. I found a solution written by Erti-Chris Eelmaa that finally solved the problem. I needed to change the Application.ShutdownMode such that the application only shuts down when Application.Shutdown(); is explicitly called.
Application.ShutdownMode = ShutdownMode.OnExplicitShutdown;
I hope this helps!

WPF: Why doesn't PageFunction return to calling Window?

In a WPF Project I am navigating to a PageFunction from a Window using a Frame that is the content of the Window. The trouble is the PageFunction doesn't return back to the calling Window. In fact, calling OnReturn(...) in the PageFunction throws an InvalidOperationException saying:
NavigationWindow of PageFunction was already closed or navigated to different content
Why does the exception get thrown?
Here is some sample code that shows the problem:
MainWindow.xaml
<Window x:Class="WpfApplication3.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:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Frame x:Name="frame" />
MainWindow Code Behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var myPageFunction = new MyPageFunction();
myPageFunction.Return += MyPageFunction_Return;
frame.Navigate(myPageFunction);
}
private void MyPageFunction_Return(object sender, ReturnEventArgs<string> e)
{
// Doesn't get here!
}
}
PageFunction.xaml
<PageFunction
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="WpfApplication3.MyPageFunction"
x:TypeArguments="sys:String"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication3"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="MyPageFunction">
<Grid>
<Button x:Name="btnReturn" Click="btnReturn_Click" Content="Return"/>
</Grid></PageFunction>
PageFunction code behind:
public partial class MyPageFunction : PageFunction<String>
{
public MyPageFunction()
{
InitializeComponent();
}
private void btnReturn_Click(object sender, RoutedEventArgs e)
{
// THIS THROWS EXCEPTION!
OnReturn(new ReturnEventArgs<string>("return"));
}
}
The window should be a NavigationWindow, i.e. you should change the base type of the MainWindow from Window to NavigationWindow, and the Return event can only be handled the calling page as documented on MSDN: https://msdn.microsoft.com/en-us/library/ms602911%28v=vs.110%29.aspx

checkbox checked or click event not firing in datatemplate

I have a checkbox in my datatemplate and for some reason the events are not firing. see code below. my datatemplate is in a resource dictionary with code behind file. Any Ideas?
<ResourceDictionary x:Class="ArmyBuilder.Templates.EquipmentDataTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<DataTemplate x:Key="EquipmentDataTemplate">
<Grid>
<CheckBox Content="{Binding Name}" Checked="ToggleButton_OnChecked" Click="CheckBox_Click"/>
</Grid>
</DataTemplate>
//code behind
namespace ArmyBuilder.Templates
{
public partial class EquipmentDataTemplate : ResourceDictionary
{
public EquipmentDataTemplate()
{
InitializeComponent();
}
private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
{
// breakpoint not hit
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
// breakpoint not hit
}
}
}
I am not sure how you use it, but the your code works for me and the click event got fired. Check the following and if you still cannot find the point, share a repro project to show how you used it.
Template XAML:
<ResourceDictionary x:Class="App10.EquipmentDataTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<DataTemplate x:Key="EquipmentDataTemplate">
<Grid>
<CheckBox Content="Click Me" Checked="ToggleButton_OnChecked" Click="CheckBox_Click"/>
</Grid>
</DataTemplate>
</ResourceDictionary>
Template cs:
namespace App10
{
public sealed partial class EquipmentDataTemplate : ResourceDictionary
{
public EquipmentDataTemplate()
{
this.InitializeComponent();
}
private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
{
// breakpoint not hit
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
// breakpoint not hit
}
}
}
In MainPage.Xaml, use the template in a ListView:
<Page
x:Class="App10.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App10"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:EquipmentDataTemplate></local:EquipmentDataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="listView" CanReorderItems="True" AllowDrop="True" ItemTemplate="{StaticResource EquipmentDataTemplate}">
</ListView>
</Grid>
</Page>
In MainPage cs:
namespace App10
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var list = new ObservableCollection<string>();
for (int i = 0; i < 10; i++)
{
list.Add("Item " + i);
}
listView.ItemsSource = list;
}
}
}

Categories

Resources