I've got MainWindow in my WPF project, into this class there is a Frame.
<Window x:Class="Gestionale.MainWindow>
<Grid>
<Frame x:Name="frameChanger"/>
<Button x:Name="Prenotation"/>
</Grid>
</Window>
When I click the button Add the frame shows the page Prenotation with this function:
public partial class MainWindow : Window
{
private void Add_Click(object sender, RoutedEventArgs e)
{
enabled_button();
camereButton.IsEnabled = false;
try
{
frameChanger.Navigate(new framePrenotation());
}
catch(Exception ex) { MessageBox.Show("Error!"); }
}
}
The page prenotation has other 3 button:
<Page x:Name="Gestionale.AddPrenotation">
<Grid>
<Button x:Name="DeletePrenotation"/>
<Button x:Name="AlterPrenotation"/>
<Button x:Name="AddPrenotation"/>
</Grid>
</Page>
I need the frameChanger references to AddPrenotation page when I click on "AddPrenotation". How can I do it?
Any guidance will be appreciated
Thanks, Davide
try to write a constructor with parameter into the Page
frameChanger.Navigate(new framePrenotation(frameChanger));`
...
public partial class framePrenotation: Page
{
private Frame frameParent;
public framePrenotation(Frame frame)
{
this.frameParent= frame;
...
}
...
}
but I don't see why you should do something like that...
Related
once to explain, I open a xaml page via "frame.content" and in this page I have opened, I want to open another one but on the frame where the second page is running.
but i can't open the page,
nothing happens. not even an expection.
So here what I have written:
This is the class from the page that is open
private void bttn_start(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.JoinNextPage();
}
This is the MainWindow class where the frame is.
public partial class MainWindow : Window
{
public void JoinNextPage() => pageMirror.Content = new page_finish();
}
You should use RoutedCommand to trigger the Frame navigation instead of the static MainWindow reference.
This removes the complete navigation logic (button event handlers) from your pages.
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public static RoutedCommand NextPageCommand { get; } = new RoutedCommand("NextPageCommand", typeof(MainWindow));
public MainWindow()
{
InitializeComponent();
CommandBindings.Add(
new CommandBinding(NextPageCommand, ExecuteNextPageCommand, CanExecuteNextPageCommand));
}
private void CanExecuteNextPageCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ExecuteNextPageCommand(object sender, ExecutedRoutedEventArgs e)
{
// Logic to select the next Frame content
JoinNextPage();
}
}
MainWindow.xaml
<Window>
<Frame>
<Frame.Content>
<Page>
<Button Command="{x:Static local:MainWindow.NextPageCommand}"
Content="Next Page" />
</Page>
</Frame.Content>
</Frame>
</Window>
Try this:
private void bttn_start(object sender, RoutedEventArgs e)
{
MainWindow mw = (MainWindow)Application.Current.MainWindow;
mw.JoinNextPage();
}
How do I navigate to the previous page in WPF but keep the data?
Suppose I have 2 pages in my app Page1 and Page2. and let's say that in page 1 the user writes some inputs for example his name, email etc...
After the user filled in his details on page 1 he navigated to page 2.
Now he wants to go back to the same page 1, how can he go back to the same page 1 with all his data?
Until now I navigated between pages by creating a new page like this:
private void PreviousButton(object sender , RoutedEventArgs e)
{
Page1 p1 = new Page1();
NavigationService.Navigate(p1);
}
You can keep a reference of Page1 in Page2:
Page1: Xaml
<Grid>
<StackPanel>
<TextBox x:Name="TxbName" Margin="10"/>
<TextBox x:Name="TxbEmail" Margin="10"/>
<Button x:Name="BtnNext" Content="Next Page" Click="BtnNext_Click"/>
</StackPanel>
</Grid>
Page1 C#
public partial class Page1
{
public Page1()
{
InitializeComponent();
}
private void BtnNext_Click(object sender, RoutedEventArgs e)
{
var page2 = new Page2(this);
NavigationService.Navigate(page2);
}
}
Page2 Xaml:
<Grid>
<StackPanel>
<Label x:Name="LblName" Margin="10"/>
<Label x:Name="LblEmail" Margin="10"/>
<Button x:Name="BtnPrevious" Content="Previous Page" Click="BtnPrevious_Click"/>
</StackPanel>
</Grid>
Page2 C#:
public partial class Page2
{
private Page1 _page1;
public Page2(Page1 page1)
{
InitializeComponent();
_page1 = page1;
}
private void BtnPrevious_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(_page1);
}
}
Try to set KeepLive = true in page attribute. Check whether it works for you.
I have created custome window (titlebar, min/max/ext buttons, own border for window manipulation and lots of styles and triggers).
There are 5 methods defined (which i would like to override):
From window markup:
SourceInitialized="Window_SourceInitialized"
Closing="Window_Closing"
From Titlebar buttons:
Exit_Click()
Max_Click()
Min_Click()
And at last I have DockPanel
<DockPanel Name="ClientArea"/>
In which I want to put my content
I have tried to add content from code:
BaseWindow editInterfaceWindow = new BaseWindow() { Owner = this };
editInterfaceWindow.DataContext = new EditInterface();
editInterfaceWindow.ShowDialog();
But this way some bindings stoped working and inside editInterfaceWindow I cant create another window this way because of Owner = this. There are also some problems with InitializeComponent() in constructor.
And ListView inside EditInterface UserControl <ListView Name="LBAvaliable" ItemsSource="{Binding AvaliableFaces, UpdateSourceTrigger=PropertyChanged}"> is not visible in code as LBAvaliable.
I have used that window few times, filling ClientArea with content by hand.
How should I create other windows, so that I can just inherit it or just define binding? So my XAML for every single window does not take ~1000 lines of code.
In the past I've used MVVMCross Framework and we never had to worry about this ourselves. Though this is not the best, here's an idea on what you can do.
Create a view model that can be overridden for your user control.
Set data templates.
Programmatically change the view model for your user control's main content and let data templates do the work for the UI.
View Model: Pre-defined 3 button actions ready for you to set/override.
public class MainUCViewModel : ViewModelBase
{
private Action<object> btnACommand;
private Action<object> btnBCommand;
private Action<object> btnCCommand;
private object ccVM;
public ViewModelBase CCVM
{
get { return this.ccVM; }
set
{
this.ccVM = value;
OnPropertyChanged(); // Notify View
}
}
public MainUCViewModel()
{
}
public RelayCommand BtnACommand
{
get { return new RelayCommand(btnACommand); }
}
public RelayCommand BtnBCommand
{
get { return new RelayCommand(btnBCommand); }
}
public RelayCommand BtnCCommand
{
get { return new RelayCommand(btnCCommand); }
}
public void SetBtnACommand(Action<object> action)
{
this.btnACommand = action;
}
public void SetBtnBCommand(Action<object> action)
{
this.btnBCommand = action;
}
public void SetBtnCCommand(Action<object> action)
{
this.btnCCommand = action;
}
}
View:
<UserControl x:Class="WpfApplication1.Views.UserControls.MainUC"
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="500" d:DesignWidth="750">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="45" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<StackPanel Orientation="Horizontal">
<Button Command="{Binding BtnACommand}" Width="100">
<TextBlock>A</TextBlock>
</Button>
<Rectangle Width="15" />
<Button Command="{Binding BtnBCommand}" Width="100">
<TextBlock>B</TextBlock>
</Button>
<Rectangle Width="15" />
<Button Command="{Binding BtnCCommand}" Width="100">
<TextBlock>C</TextBlock>
</Button>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<ContentControl x:Name="CCMain" Content="{Binding CCVM}"/>
</Grid>
</Grid>
</UserControl>
Look at Thinking with MVVM: Data Templates + ContentControl. Simply define the data template for your view model.
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModel:GeneralSettingsViewModel}">
<View:GeneralSettingsView/>
</DataTemplate
<DataTemplate DataType="{x:Type ViewModel:AdvancedSettingsViewModel}">
<View:AdvancedSettingsView/>
</DataTemplate>
</Window.Resources>
What I’m saying here is that GeneralSettingsViewModel should be
rendered using a GeneralSettingsView. That’s exactly what we need !
Because the Views are created using a DataTemplate, we do not need to
setup the DataContext, it will be automatically registered to the
templated object, the ViewModel.
There are two main approaches to your problem:
Inherited windows
Configurable windows
For approach 1, design your window and make the methods overrideable:
In base window xaml, assign the handlers and everything you want:
<Window x:Class="WpfTests.MainWindow"
...
SourceInitialized="Window_SourceInitialized">
In base window, define the handlers as protected virtual (or abstract, if you like to enforce their implementation)
public partial class MainWindow : Window
{
// ...
protected virtual void Window_SourceInitialized(object sender, EventArgs e)
{
}
// ...
}
Create derived windows
public class ExWindow : MainWindow
{
protected override void Window_SourceInitialized(object sender, EventArgs e)
{
// specialized code here
}
}
Change App.xaml to use Startup instead of StartupUri
<Application x:Class="WpfTests.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup">
And manually create your first window, chosing one of the inherited window classes
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
var window = new ExWindow();
window.Show();
}
}
The second approach - configurable windows - follows the same principle as a good user control design: The window/control properties are controlled by the creator instead of being controlled by the window/control itself.
So, instead of defining some event handler within the window code, just leave this exercise to the user, who hopefully knows what the window should do:
public partial class MainWindow : Window
{
// I don't care for SourceInitialized (also remove it from XAML)
}
In App.xaml or wherever a window is created:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
var window = new MainWindow();
window.SourceInitialized += window_SourceInitialized;
window.Show();
}
void window_SourceInitialized(object sender, EventArgs e)
{
var window = sender as MainWindow;
// I know how to handle this event for this window instance
}
}
How to add an UI controller to all pages of the app? For example, having the same SplitView controller with navigation menu in Pane on all pages without copying its xaml code? Or maybe changing App.xaml in some way?
Or, as a second option, is it possible to create a UserControl that contains SplitView and put all other views on this page inside it Content? I mean, how to put views into the UserControl in xaml (or even in code)?
Create custom RootControl which derives from UserControl class and which contains the root Frame
<SplitView DisplayMode="CompactOverlay">
<SplitView.Pane>
<StackPanel>
<AppBarButton Icon="Home"
Width="50"
MinWidth="50"
Click="OnHomeClicked"
/>
<AppBarButton Icon="Shop"
Width="50"
MinWidth="50"
Click="OnShopClicked"/>
<AppBarButton Icon="Setting"
MinWidth="50"
Width="50"
Click="OnSettingsClicked"/>
</StackPanel>
</SplitView.Pane>
<SplitView.Content>
<Grid>
<Frame x:Name="rootFrame"/>
<!--Put your hamburger button here-->
</Grid>
</SplitView.Content>
</SplitView>
Rewrite OnLauched:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
var rootControl = Window.Current.Content as RootControl;
if (rootControl == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootControl = new RootControl();
rootControl.RootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootControl;
}
if (rootControl.RootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootControl.RootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
and you can manage you actions from code-behind or ViewModel for navigation and other actions
public sealed partial class RootControl : UserControl
{
private Type currentPage;
public RootControl()
{
this.InitializeComponent();
RootFrame.Navigated += OnNavigated;
}
private void OnNavigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
currentPage = e.SourcePageType;
}
public Frame RootFrame
{
get
{
return rootFrame;
}
}
private void OnHomeClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Navigate(typeof(MainPage));
}
private void OnShopClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Navigate(typeof(StorePage));
}
private void OnSettingsClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Navigate(typeof(SettingsPage));
}
private void Navigate(Type pageSourceType)
{
if (currentPage != pageSourceType)
{
RootFrame.Navigate(pageSourceType);
}
}
}
Download the sample and look how it works
It sounds like you're after something like what Jerry Nixon suggests in this article here.
The essential idea is that instead of a Frame control hosting all of your app's content, you create a "Shell" (in the article's case, made of a SplitView, but really, it could probably be anything), which has some content of its own, as well as a Frame control (which then hosts the rest of your content).
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;
}
}
}