I am very new to C# and the WPF Architecture. I am trying to create an application with simple page Navigation. I have changed my MainWindow from Window to NavigationWindow. I have also put the following code in MainWindow.xaml.cs
public void View(string newView)
{
Uri view = new Uri(newView, UriKind.Relative);
NavigationService nav = NavigationService.GetNavigationService(this);
if (nav != null)
{
nav.Navigate(view);
}
else
{
MessageBox.Show("NavNull");
}
}
I am calling this method from the default source ("HubView.xaml") this is in a folder called "Pages". The code looks like this
public void Button_Click(object sender, RoutedEventArgs e)
{
View = #"\Pages\UserAdd.xaml";
MainWindow mainWindow = new MainWindow();
mainWindow.View(View);
}
However when I click the button the message box is displayed indicating that nav equals null. I have read through this question and the subsequent answer, however I still do not fully understand.
Any suggestions would be greatly appreciated!
Edit:
This is the "MainWindow.xaml":
<NavigationWindow x:Class="Container.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ResizeMode="CanMinimize"
Title="MainWindow" Height="350" Width="525" Source="Pages/HubView.xaml" WindowStyle="ThreeDBorderWindow" ShowsNavigationUI="False">
</NavigationWindow>
As you can see the Window is a Navigation Window.
NavigationService is for page navigation in WPF like in a browser and for that to work you would need to add a Frame to your MainWindow.xaml
<Grid>
<Frame x:Name="mainFrame"/>
<Button x:Name="btnPage1" Content="Page 1" Width="200" Height="50"
Click="btnPage1_Click"/>
</Grid>
and use NavigationService to navigate eg
private void btnPage1_Click(object sender, RoutedEventArgs e)
{
mainFrame.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.Relative));
}
EDIT
Create 1 window and 2 pages
MainWindow.xaml
<NavigationWindow 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" Source="Page1.xaml">
Page1.xaml
<Page x:Class="WpfApplication1.Page1"
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="Page1">
<Grid>
<TextBlock Text="Page 1" FontWeight="Bold" />
<Button Margin="0,40" Content="Goto Page 2" Width="200" Height="50"
Click="Button_Click"/>
</Grid>
Page1.xaml.cs
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("Page2.xaml", UriKind.Relative));
}
}
NavigationWindow has a property of NavigationService so no need to create new variables. Hope that helps.
NOTE Page2.xaml is just a blank page
Related
I really don't know how to search to find a solution to this (I googled a lot, maybe I'm blind...).
I have a ComboBox which also contains a TextBox. The ComboBox is instantiated in a separate Control.xaml with a specific DataContext, where it gets its content for the Popup list.
Now when I type something into the TextBox, I want to trigger a method which then filters the list of my DataContext for the specific elements.
So my ComboBox.cs has some of the following content:
public event EventHandler FilterTextChanged;
protected virtual void OnFilterTextChanged(EventArgs args)
{
FilterTextChanged?.Invoke(FilterText, args);
}
public string FilterText
{
get { return _filterText; }
set
{
//This point is reached when I type something into the TextBox within the ComboBox
if (_filterText == value) return;
_filterText = value;
OnFilterTextChanged(EventArgs.Empty);
OnPropertyChanged("FilterText");
}
}
And in my Control.xaml, I have configured it like this:
<my:ComboBox x:Name="FURecipeComboBox"
AuthorizationMode="IsEnabled"
IsTextSearchEnabled="False"
StaysOpenOnEdit="True"
FilterTextChanged="FURecipeComboBox_OnFilterTextChanged"
ItemsSource="{Binding RecipeFileNames}"
SelectedItem="{Binding Value, Delay=100, ElementName=AlphaNumericTouchpadTextVarIn}"
d:DataContext="{d:DesignInstance {x:Type adapter:ToolRecipeVariableInfo}, IsDesignTimeCreatable=False}">
</my:ComboBox>
But I just can't get it to catch the event "FilterTextChanged", and my method "FURecipeComboBox_OnFilterTextChanged" will not be reached anytime...
I would be really really glad for some hints or help!
Kind regards
BB
Have a look at RoutedEvents at microsoft docs
This is a example post from Stackoverflow
In your case try to change EventHandler to RoutedEventHandler.
I made a small example:
Main.xaml
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:UserControl1 HorizontalAlignment="Left" Height="207" Margin="348,175,0,0" VerticalAlignment="Top" Width="311" MyClick="UserControl1_MyClick"/>
</Grid>
Main.cs
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void UserControl1_MyClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Yep");
}
}
}
control.cs
public partial class UserControl1 : UserControl
{
public event RoutedEventHandler MyClick;
public UserControl1()
{
InitializeComponent();
}
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
if (MyClick != null)
MyClick(this, new RoutedEventArgs());
}
}
}
control.xaml
<UserControl x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
d:DesignHeight="372.313" d:DesignWidth="350">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="218" Margin="59,54,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="202" KeyDown="textBox_KeyDown"/>
</Grid>
Hi i am making a WPF application.
I have a mainwindow, which i have my navigation in, then i also have a stackpanel, with this:
<Frame x:Name="_mainFrame" NavigationUIVisibility="Hidden"/>
inside, where i place my pages inside.
In My mainwindow i navigate to other pages using the following to for example move to the gameWindow:
private void NavigateGameWindow(object sender, RoutedEventArgs e)
{
_mainFrame.Navigate(new GameWindow());
}
This works fine, but now that i am inside that window (gameWindow), i am checking if a "player" is set, if not, i want to navigate to another page, where i can set certain values.
and then navigate back to GameWindow.
But how do i get a hold of _mainFrame, when it is a part of the mainwindow ?
It says in GameWindow on _mainFrame
The name _mainFrame, does not exist in the current context
Game Window
public partial class GameWindow
{
private int numberOfPlayers;
private Player[] players;
private INavigator _navigator;
public GameWindow(INavigator navigator)
{
_navigator = navigator; //assign navigator so i can navigate _mainframe to other pages.
// initialize game properties, check if they are set.
var gameProp = new GameProperties();
this.numberOfPlayers = 2;
this.players = gameProp.CheckPlayerIsSet(this.players);
//check if a player has been set
if (this.players != null)
{ // Player is set or has been set. proceed or start the game.
InitializeComponent();
}
else
{ // redirect to settings window because players has not been set!
_navigator.Navigate(new GameSettings());
}
}
}
Main Window
public partial class MainWindow : Window, INavigator
{
public MainWindow()
{
InitializeComponent();
}
private void ExitGame(object sender, RoutedEventArgs e)
{
System.Windows.Application.Current.Shutdown();
}
public void Navigate(Page p)
{
_mainFrame.Navigate(p);
}
private void NavigateRulesWindow(object sender, RoutedEventArgs e)
{
Navigate(new GameRulesWindow());
}
private void NavigateGameWindow(object sender, RoutedEventArgs e)
{
Navigate(new GameWindow(this));
}
}
GameSettings
public partial class GameSettings : Page
{
public GameSettings()
{
InitializeComponent();
//var gameProps = new GameProperties();
// set number of players,, should prompt user, and get value!
//gameProps.SetNumberOfPlayers(2);
}
}
View for gamesettings
<Page x:Class="ITD.OOP_Projekt.WPF.Menu.GameSettings"
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:ITD.OOP_Projekt.WPF.Menu"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="GameSettings">
<Grid Background="white">
<TextBox HorizontalAlignment="Left" Height="23" Margin="229,144,0,0" TextWrapping="Wrap" Text="This is game settings" VerticalAlignment="Top" Width="120"/>
</Grid>
</Page>
One very easy solution is this:
So with the following code you have only one Window (Mainwindow) and inside that Window you display your pages. You can compare it with your internet browser. You have one window and inside that window you can navigate between pages (settings, game, highscore, ...).
I hope this helps and you can get it to work!
If not i can try to upload a simple example to github in the evening.
Just get rid of your GameWindow and implement it as a page.
MainWindow
xaml:
<Window x:Class="PageSwitcher.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:PageSwitcher"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Frame x:Name="MainFrame" NavigationUIVisibility="Hidden" />
</Grid>
cs:
public partial class MainWindow : INavigator
{
public MainWindow()
{
InitializeComponent();
Navigate( new Page1(this) );
}
public void Navigate( Page p )
{
MainFrame.Navigate( p );
}
}
Page1
xaml:
<Page x:Class="PageSwitcher.Page1"
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:PageSwitcher"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Page1">
<Grid Background="Green">
<Button Width="150" Height="30" Click="ButtonBase_OnClick" Content="Go to Page2" />
</Grid>
cs:
public partial class Page1 : Page
{
private INavigator _navigator;
public Page1(INavigator navigator)
{
_navigator = navigator;
InitializeComponent();
}
private void ButtonBase_OnClick( object sender, RoutedEventArgs e )
{
_navigator.Navigate(new Page2(_navigator));
}
}
Page2
xaml:
<Page x:Class="PageSwitcher.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"
xmlns:local="clr-namespace:PageSwitcher"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Page2">
<Grid Background="Blue">
<Button Width="150" Height="30" Click="ButtonBase_OnClick" Content="Go to Page1"/>
</Grid>
cs:
public partial class Page2 : Page
{
private INavigator _navigator;
public Page2(INavigator navigator)
{
_navigator = navigator;
InitializeComponent();
}
private void ButtonBase_OnClick( object sender, RoutedEventArgs e )
{
_navigator.Navigate(new Page1(_navigator ));
}
}
Thats all you really need.
In this example you can switch between two pages on button click events.
Just start a new wpf project and copy the code.
Play around with it until you understand it and then try to implement it in your game :)
If you want to redirect the page from one page to another you can create one method or function in which you can write the conditions and use the below code for redirection. It will take care of the directory also.
NavigationService.Navigate(new Settings.LatestActiveUsers());
So I have a user interface which has several controls which I want to persist. One of these controls is a button that is supposed to swap between a view and an edit mode. Each of these will have many controls in them that will need to be accessible later on. My main page is defined as follows, with irrelevant stuff stripped down of course.
MapView.xaml
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TripPhotoMapper"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Maps="using:Windows.UI.Xaml.Controls.Maps"
x:Class="TripPhotoMapper.MapView"
mc:Ignorable="d">
<Grid x:Name="grid_main">
<Maps:MapControl x:Name="map_main" MapTapped="MapUserTapped"/>
<StackPanel x:Name="stack_edit_mode">
<Border Tapped="ButtonEditMode">
<TextBlock Text="Edit Mode"/>
</Border>
</StackPanel>
<Grid x:Name="grid_swap_interface">
here is where I want the swapable interfaces
</Grid>
</Grid>
</Page>
MapView.xaml.cs
namespace TripPhotoMapper
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MapView : Page
{
private EditMode _mode_edit;
private ViewMode _mode_view;
private Control _mode_current;
public MapView()
{
this.InitializeComponent();
_mode_edit = new EditMode();
_mode_view = new ViewMode();
_mode_current = _mode_view;
grid_swap_interface.Children.Add(_mode_current);
}
public static class GlobalVars
{
...
//this keeps track on if we are in edit mode
public static bool glo_edit_mode = false;
}
...
private void MapUserTapped(MapControl sender, MapInputEventArgs args)
{
...
//this is the problem
ViewMode.txtblc_view_mode.Text = "hi";
}
//editing controls
private void ButtonEditMode(object sender, TappedRoutedEventArgs e)
{
grid_swap_interface.Children.Clear();
if (GlobalVars.glo_edit_mode == false)
{
_mode_current = _mode_edit;
}
else
{
_mode_current = _mode_view;
}
grid_swap_interface.Children.Add(_mode_current);
}
}
}
I then have two other very barebones xaml files for the two interfaces.
EditMode.xaml
<UserControl
x:Class="TripPhotoMapper.EditMode"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TripPhotoMapper"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<Button/>
</Grid>
</UserControl>
ViewMode.xaml
<UserControl
x:Class="TripPhotoMapper.ViewMode"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TripPhotoMapper"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<TextBlock x:Name="txtblc_view_mode" Text="view mode"/>
</Grid>
</UserControl>
I haven't touched the C# for either of these two additional xaml's yet. So they're just like this.
EditMode.xaml.cs
namespace TripPhotoMapper
{
public sealed partial class EditMode : UserControl
{
public EditMode()
{
this.InitializeComponent();
}
}
}
So I've figured out how to swap between the two interfaces without any issue; the button and textblock do both appear as they should. However, I included (for testing) a function to change the text in txtblc_view_mode to "hi", but I'm given the following error:
'ViewMode.txtblc_view_mode' is inaccessible due to its protection level
I'm incredibly new to splitting up files like this and I can't figure out how to fix it. I've found something mentioned in a few posts
x:FieldModifier="public"
but I don't know where to put it. Could anyone help me? Once the interfaces are properly split up, a lot of controls in each will have to be modified in code and thus I'll need to fix this problem.
Can't try this for now but you can check it out.
Add/modify the following code in your ViewMode cs:
public sealed partial class ViewMode : UserControl
{
public static ViewMode Current { get; private set; }
public ViewMode()
{
this.InitializeComponent();
Current = this;
}
}
And maintain the x:FieldModifier="public" in your desired control (TextBlock) to be edited/modified.
<TextBlock x:Name="txtblc_view_mode" x:FieldModifier="public" Text="view mode"/>
On EditMode cs, add in your methods:
public void ChangeTxtBlockText()
{
TextBlock tb = ViewMode.Current.txtblc_view_mode as TextBlock;
if (tb != null)
{
tb.Text = "Hi";
}
}
I am having an strange issue with clicking a button. When I click on a button, it is not registered as a click unless I move the mouse before I release the left button. Below is what I used in a new program to verify I didn't do something in the program I was working on.
I am using a Raspberry Pi 2 and build version 10.0.16212.1000
xaml:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="175,216,0,0" VerticalAlignment="Top" Click="button_Click"/>
</Grid>
</Page>
c#:
namespace App1
{
/// <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();
}
private void button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Button Clicked");
}
}
}
I'm building a Universal Windows Platform app where I have a few controls on the MarvelMenu.xaml page and I need to be able to control them from the MainPage.xaml, especially the MyProgressRing control. For that I created a helper method called Search in the MarvelMenu.xaml page as follows:
public partial class MarvelMenu : Page
{
public async void Search(ObservableCollection<Character> MarvelCharacters, string searchedCharacter)
{
MyProgressRing.Visibility = Visibility.Visible;
MyProgressRing.IsActive = true;
DataModel.ErrorMessage = "";
DataModel.MarvelCharacters.Clear();
Task t = MarvelFacade.PopulateMarvelCharactersByNameAsync(searchedCharacter, MarvelCharacters);
await t;
MyProgressRing.IsActive = false;
MyProgressRing.Visibility = Visibility.Collapsed;
}
}
My problem is that those commands don't work. Other methods on this same page do the same command and it works fine, but because this method is called from the "MainPage.xaml", as follows, it doesn't work.
public partial class MainPage : Page
{
private MarvelMenu _MarvelMenu = new MarvelMenu();
private DataModel _DataModel = new DataModel();
public void AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
_MarvelMenu.Search(_DataModel.MarvelCharacters, sender.Text);
_MarvelMenu.MyProgressRing.Visibility = Visibility.Visible;
}
}
Although the Task t in the Search method is executed just fine... Point being, the XAML code is not working... And below is a part of it, the MyProgressRing that isn't working.
<Page x:Class="Marvel_sDatabase.Views.MarvelMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Marvel_sDatabase.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:Marvel_sDatabase.Models"
Loaded="Page_Loaded"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ProgressRing Name="MyProgressRing"
x:FieldModifier="public"
Grid.Column="1"
Grid.RowSpan="3"
Width="50"
Height="50"
Foreground="{ThemeResource SystemControlBackgroundAccentBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Grid>
</Page>
I would really appreciate any help, as I'm a hobby and newbie to developing apps.