wpf Load page into the <grid> on button click - c#

i have this code but i want to load frame from xaml.cs because changeing combobox item i want to load different pages. i know how to load page on grid but if i make this i cant change pages whenever combobox item changed
<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="822.702" Width="805.597">
<StackPanel >
<Grid>
//there is some text labels
</Grid>
<Grid heigt="150" margin="0,450,0,0">
<Frame Source="page1.xaml"></Frame>
</Grid>
</StackPanel>
if i make this page1 will be loaded on grid but
if i give some name like GRD1
<Grid heigt="150" margin="0,450,0,0" x:name="GRD1">
</Grid>
and if I want to define the frame source in xaml.cs using c# how can I define this function
<Frame Source="page1.xaml"></Frame>
I know that I ask a particular question but I need that the pages in grid can be variable every time combobox changes value. thank !!!!

i find the best way for load
<Grid>
<Frame x:name="load_frame"/>
</Grid>
this is what to do on xaml
and then on button click or combobox value change or what you want you can load any page like this
private void Button_Click(object sender, RoutedEventArgs e)
{
load_frame.Content = new ANYPAGEYOUWANT();
}
I am writing this answer because I have seen that many people are trying to load page manually
thank you Jonathan Perennes
PS. I Forgot if you don't want to show navigatebar you must add
<Frame x:Name="load_frame" NavigationUIVisibility="Hidden"/>

If you want display specific view based on some criteria (selected item of a combobox for your case), i recommand you to use ContentControl and DataTemplateSelector
Edit : Pseudo code
In your window ressource create datatemplate based on the different views you want to display :
<DataTemplate x:Key="page1View">
<Views:page1/>
</DataTemplate>
<DataTemplate x:Key="page2View">
<Views:page2/>
</DataTemplate>
Then create a datatemplate selector that derivate from the datatemplate selector class : Exemple of implementation
In the datatemplate selector's SelectTemplate method you can return the good datatemplate either by using "FindResource" methods or by creating datatemplate properties in your datatemplateselector class and link them to your datatemplate declared in the xaml
Than add it in your window ressources :
<local:MyDataTemplateSelector x:Key="MyDataTemplateSelector" />
Then use a contentcontrol that will display the right view based on your combobox selected item by using the template selector
<ContentControl Content="{Binding ComboboxSelectedItem}" ContentTemplateSelector="{StaticResource MyDataTemplateSelector }"/>

Related

UWP Pivot control, how to set focus to first control within PivotItem

I have a Pivot control that uses an ItemsSource to bind to a list of ViewModel instances. I assign a custom ItemTemplateSelector to map between ViewModel types and DataTemplate definitions. This all works fine and the correct display is created for each ViewModel based on the associated DataTemplate. Something like this...
<Pivot ItemsSource="{x:Bind ViewModels}"
ItemTemplateSelector="{StaticResource ViewModelSelector}"
SelectedItem="{x:Bind SelectedViewModel, Mode=TwoWay}"/>
The problem is that I want to automatically set focus to a control within each page when that page is first shown. They are typically data entry forms and so the user currently has to select the first control to start entering data. It would be better if first showing a page automatically then set focus to a control on that page.
Any ideas?
You could bind a method to the TextBox when it's loaded.
For example:
<Pivot.ItemTemplate>
<DataTemplate x:DataType="local:Test">
<TextBox Text="{x:Bind Content}" Height="50" Loaded="{x:Bind TextBox_Loaded}">
</TextBox>
</DataTemplate>
</Pivot.ItemTemplate>
public void TextBox_Loaded(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
textBox.Focus(FocusState.Programmatic);
}
}

How can I access a named element of a ControlTemplate through code-behind?

I want to access one of the named elements within the original control template that another element is using, in the code-behind.
This is an example of the XAML code (obviously the original is more complicated, or I'd just be doing this in XAML):
<Window x:Class="Temp.MainWindow" Title="MainWindow">
<Window.Resources>
<ControlTemplate x:Key="MyTemplate" TargetType="{x:Type Expander}">
<Expander Header="Some header">
<StackPanel>
<Grid Name="MyGrid"/>
</StackPanel>
</Expander>
</ControlTemplate>
</Window.Resources>
<Grid>
<Expander Name="expander" Template="{DynamicResource MyTemplate}"/>
</Grid>
</Window>
What I've tried:
public MainWindow()
{
InitializeComponent();
Grid grid = expander.Template.FindName("MyGrid", expander) as Grid;
}
I've also tried
Grid grid = expander.Template.Resources.FindName("MyGrid") as Grid;
But g is always null.
I've looked at:
How do I access an element of a control template from within code behind?
How to access a WPF control located in a ControlTemplate
How do I programmatically interact with template-generated elements Part I
The links above are how I got the code I'm working with, but for some reason, g is just always null. Am I doing something wrong with the ContentTemplate? Any help would be appreciated!
You need to wait until the template is applied to the control
protected override OnApplyTemplate()
{
Grid grid = Template.FindName("YourTemplateName") as Grid;
}
The real problem here is that you're mixing technologies. You're attempting to use something meant for grabbing the template of a lookless control, in the behind code of the main window. I would be surprised if you didn't run into more issues.
Instead, I would suggest looking into How to Create Lookless Controls and redesigning your application. It wouldn't take much effort and it would all play nice together.

WPF Custom TabItem - Controls not displayed in Visual Studio Designer

I created a custom TabItem with a DockPanel and a Button in it.
XAML:
<TabItem
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"
mc:Ignorable="d" x:Class="MovieDB.UI.UserControlls.SearchTab" d:DesignWidth="500.038" d:DesignHeight="309.055">
<DockPanel Background="#FFE5E5E5">
<Button x:Name="button" Content="Button" Height="100" Width="75" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</DockPanel>
</TabItem>
C#:
namespace MovieDB.UI.UserControlls
{
/// <summary>
/// Interaktionslogik für SearchTab.xaml
/// </summary>
public partial class SearchTab : TabItem
{
private SearchContainer<SearchMovie> results;
public SearchTab()
{
InitializeComponent();
this.Header = "Suche";
}
public SearchTab(SearchContainer<SearchMovie> results):this()
{
this.updateSearch(results);
}
public void updateSearch(SearchContainer<SearchMovie> results)
{
clear();
if(results.TotalResults == 0)
{
}
else
{
this.results = results;
Debug.WriteLine("Results: " + results.Results.Count());
}
}
private void clear()
{
}
}
}
If launch my program the button is displayed (Screenshot 2). But the button and i guess the panel itselve does noch show up in the Visual Studio 2015 Designer (Screenshot 1).
Where is the Problem?
If you put the TabItem in a TabControl it works fine.I think that's the Problem.
The designer needs a navigation control like TabControl,Window Page etc. as root.
<TabControl x:Class="CustomControls.tab"
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:DesignWidth="500.038" d:DesignHeight="309.055">
<TabItem>
<DockPanel Background="#FFE5E5E5">
<Button x:Name="button" Content="Button" Height="100" Width="75" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</DockPanel>
</TabItem>
</TabControl>
What you did should work. But it doesn't, and I'll later try to show why.
But first, my workaround:
open designer, and right-click on it,
select: Edit Additional Templates, then Edit Generated Content, then Create Empty... Give your new DataTemplate a name, say 'DataTemplate1'
Designer will generate some code - an empty DataTemplate with a key DataTemplate1, and it will add your to TabItem the ContentTemplate attribute, with DataTemplate1 assigned to it (by DynamicResource).
Now move the content of your TabItem to the DataTemplate1. The designer should correctly display your layout.
If you close and reopen your SearchTab control, you'll find that you can't see the content again. To have it back right click on the designer, select Edit Additional Template, then Edit Generated Content, then Edit Current.
Why the designer couldn't load your SearchTab? If you right-click on the designer and select Edit Template, then Edit a Copy... you'll have TabItem style generated. The header of the TabItem is displayed by the ContentPresenter, while the TabItem's content must by displayed inside the innerBorder Border. This border has Opacity set to zero, and it's being changed to 1 by MultiTriggers, which are dependent on the TabControl. The TabControl in your case doesn't exist, so all the bindings are broken. Which suggests, that changing a default Style for 'TabItem', would also solve your problem.
Although I do not have my dev machine to work with, I can only offer a suggestion. For whatever you want on your tab item control, why not put all your controls in a custom user control or grid with the premise that you KNOW you will be adding it to tab control that is dynamically added to your tab page.
The tab item needs its proper parent tab control to render it in the designer. But if you build everything as a standard control make it look and operate as you expect.
Then at run-time, add your tab item, then add the custom control to your dynamically added tab item and see if that works for you. You apparently have all the other components / processes working. Even if your sample control was just a label, textbox or something similar.

How to handle a DataTemplate inside a tab?

My name is Andrea this is my first post ever.
Frequently you have helped me as a simple reader, now I'm writing because I wanted to direct support.
I have to create and a tab control and with a button "Add Tab" I have to add a new tab with the same content.
Up to this everything is fine.
Within Tab I have a textedit and a combobox.
My problems are two:
1 How do I load the contents of the combobox for each tab I add?
2 Every time I write the text of and a edit tab override also edit the text of the other tab.
Here the code:
Data Template in Xaml:
<DataTemplate x:Key="tabItemContent">
<dxlc:LayoutGroup Orientation="Vertical" Header="Target Description" IsCollapsible="True">
<!--Name-->
<dxlc:LayoutItem>
<dxlc:LayoutGroup Orientation="Horizontal" ItemSpace="4" >
<dxlc:LayoutItem Label="Name" Margin="10">
<dxe:TextEdit x:Name="TextEdit_NameTarget"/>
</dxlc:LayoutItem>
</dxlc:LayoutGroup>
</dxlc:LayoutItem>
<!--Nation e Label-->
<dxlc:LayoutItem>
<dxlc:LayoutGroup Orientation="Horizontal" ItemSpace="12" >
<dxlc:LayoutItem Label="Nation" Margin="10">
<ComboBox x:Name="ComboBox_TargetNazione" />
</dxlc:LayoutItem>
</dxlc:LayoutGroup>
</dxlc:LayoutItem>
</dxlc:LayoutGroup>
</DataTemplate>
C#:
private void Button_Click_Add(object sender, RoutedEventArgs e)
{
DataTemplate tabItemDataTemplate = this.TryFindResource("tabItemContent") as DataTemplate;
DXTabItem tabItem = new DXTabItem();
tabItem.Header = "New Tab";
tabItem.ContentTemplate = tabItemDataTemplate;
tabControl_Targets.Items.Add(tabItem);
}
Here's where to load the list into the combobox:
private void LoadComboBoxNation()
{
ComboBox_TargetNazione.ItemsSource =
ManagementTriple.Istance().get_Nation_byTipologyAndContext(ComboBox_TypologyScenario.SelectedItem.ToString(),
ComboBox_ContextScenario.SelectedItem.ToString());
controlloselecteditem(ComboBox_SourceNazione.SelectedItem.ToString());
controlloselecteditem(ComboBox_TargetNazione.SelectedItem.ToString());
}
Thank you all for the help that you can give me.
DataTemplates require a simple but fundamental requirement to work properly: you should use the ViewModel-First approach.
Ideally, your tab control should have a Binding to some ViewModel. Then, if you want another tab to appear, you should use your button click to call a Command in your ViewModel, then the ViewModel would add another item to your TabControl ItemsSource property (which would be some collection), and the new item would be displayed "automagically" with its respective DataTemplate.
The idea of WPF is to replace all this imperative code in the View (like the one you posted) with a more indirect one, where your only worry is to manipulate things in the ViewModel, and the "Dumb View" just follows.
Hope this helps, but don't hesitate to ask for additional details in the comments.

access-like data navigation in WPF?

What would be the best way to build a data-navigation like in access-forms in XAML/C#?
Should I build a user control (or even custom control) that I just bind to my collection in which I can put other controls? (hence this question: C# User Control that can contain other Controls (when using it) )
Or can I build something by deriving from then ItemsControl somehow? how?
Or would this be done completely different today (like "this style of navigation is so last year!")?
I'm relatively new to C# and all (not programming as such, but with more like "housewife-language" Access-VBA) also I'm no native english speaker. So pls be gentle =)
You can create user control and place a bunch of buttons (First, Prev, Next, Last, etc..) in it and place it on the main window. Secondly, you can bind your data navigation user control to a CollectionViewSource which will help you to navigate among your data.
Your main window:
<Window.Resources>
<CollectionViewSource x:Key="items" Source="{Binding}" />
</Window.Resources>
<Grid>
<WpfApplication1:DataNavigation DataContext="{Binding Source={StaticResource items}}" />
<StackPanel>
<TextBox Text="{Binding Source={StaticResource items},Path=Name}" />
</StackPanel>
</Grid>
Your Data Navigation User Control:
<StackPanel>
<Button x:Name="Prev" Click="Prev_Click"><</Button>
<Button x:Name="Next" Click="Next_Click">></Button>
<!-- and so on -->
</StackPanel>
And your click handlers goes like this:
private void Prev_Click(object sender, RoutedEventArgs e)
{
ICollectionView view = CollectionViewSource.GetDefaultView(DataContext);
if (view != null)
{
view.MoveCurrentToPrevious();
}
}
I hope this helps.
Sounds like you're after a DataGrid control. Microsoft is releasing a WPF DataGrid as part of a WPF Toolkit which you can download here: http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=25047.

Categories

Resources