Load a Page into a ContentControl - xaml

I have a ContentControl where I want to load the page myPage2. My XAML Codefrom this page looks like this:
<Page x:Class="ExampleApp.myPage2">
<Grid x:Name="Content" Height="651" Width="941" Background="White">
...
...
</Grid>
</Page>
I know that I can load a resource from a page with this Code:
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
var contentControl = (ContentControl)container;
return (DataTemplate) contentControl.Resources[templateKey];
}
My problem now is that I can't load a page like above with this code. I have to write this:
<Page x:Class="ExampleApp.myPage2">
<Page.Resources>
<DataTemplate x:Key="Test">
<Grid x:Name="Content" Height="651" Width="941" Background="White">
...
...
</Grid>
</DataTemplate>
</Page.Resources>
</Page>
And then I can load the page with the same Code from above with templateKey="Test". But the main problem is that I want to use the first declaration of the page and do not want to use <Page.Resources> <DataTemplate x:Key="Test"> and so on. I want to load the site direcly from the first declaration (first code in this post). How can I create a DataTemplate directly from a page? Or is there an other way to load a page into a ContentControl?

There is no reason to use a Page within a ContentControl. A Page is a subclass of the UserControl class that adds support for being used within a Frame control to support navigation, back stack/history, etc. You should probably replace Page with UserControl in XAML and code behind, so you would end up with something like this:
<UserControl x:Class="ExampleApp.myControl2">
<Grid x:Name="Content" Height="651" Width="941" Background="White">
...
...
</Grid>
</UserControl>
You can put the UserControl itself in a DataTemplate if you want to use it as a DataTemplate in a ContentControl:
<ContentControl
xmlns:controls="using:ExampleApp">
<ContentControl.Resources>
<DataTemplate
x:Key="Test">
<controls:myControl2 />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>

Related

Binding with Prism Navigation

I'm trying to bind string path in XAML using prism navigateto extension method from a button in ListView.
Apparently the BindingContext isn't recognized to be the same as in the ListView
Here's the sample code of what i'm trying to achieve.
<ListView
x:Name="MainMenu"
CachingStrategy="RetainElement"
HasUnevenRows="True"
ItemsSource="{Binding MenuItems}"
Margin="20,0,0,0"
SeparatorVisibility="Default">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<buttons:SfButton
Style="{StaticResource BaseButtonStyle}"
HeightRequest="70"
TextColor="{StaticResource MenuTextColor}"
Text="{Binding Title}"
HorizontalTextAlignment="Start"
VerticalOptions="CenterAndExpand"
HorizontalOptions="FillAndExpand"
ImageSource="{Binding MenuItemType, Converter={StaticResource MenuItemTypeConverter}}"
ShowIcon="True"
Command="{prism:NavigateTo Name={Binding Item.View}}"
/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Any ideas how to set the binding in this situations?
Regards.
Within any sort of ListView, CollectionView, etc where you are binding an ItemsSource and then have some sort of DataTemplate to display an individual item in that collection, the Binding Context within that DataTemplate is the individual item in the collection not the ViewModel that that provides the Binding Context of both your Page and the ListView.
There are technically a couple parts to this that you will want to understand. Let's say that your model looks like:
public class FooModel
{
public string Text { get; set; }
public string NavigationPath { get; set; }
}
And let's say that you have a collection of FooModel like:
public ObservableCollection<FooModel> FooItems { get; }
In XAML you might have something like:
<ListView ItemsSource="{Binding FooItems}">
However when you go to reference properties of FooItem you will just reference them like:
<ListView.DataTemplate>
<DataTemplate>
<ViewCell>
<Button Text="{Binding Text}"
Command="{prism:NavigateTo Name={Binding NavigationPath}" />
</ViewCell>
</DataTemplate>
</ListView.DataTemplate>
Now assuming that the issue isn't that you're just adding Item erroneously, let's look at some other possible issues/solutions. To start let's look at the start of our page.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="http://prismlibrary.com"
x:Name="page"
x:Class="HelloWorld.Views.ViewA">
The big thing to notice here is that I've added the x:Name attribute so that I can reference the page itself later. In general within the context of something like a ListView if I need to access say the FooCommand property within my ViewModel I might would change my XAML markup from:
<Button Command="{Binding FooCommand}" />
To instead look at the Page's BindingContext like this:
<Button Command="{Binding BindingContext.FooCommand, Source={x:Reference page}}" />
While this will help you in general within your ListView it still doesn't necessarily help you with the issue of using Prism's Navigation Extensions. For this you may need to pass in the SourcePage like the following:
<Button Command="{prism:NavigateTo 'Foo', SourcePage={x:Reference page}}" />
In the event this doesn't work for some reason then you may be possible that the BindingContext isn't getting set properly on the Navigation Extension itself. To work around this you would want to update your command as follows:
<Button x:Name="cellButton"
Command="{prism:NavigateTo Name={Binding View},
BindingContext={x:Reference cellButton}}" />
Note that if you need to reference the SourcePage or add the BindingContext to resolve your issue, please provide a sample that reproduces the issue and open an issue on GitHub.

How to Bind Parallax View within GridView DataTemplate?

I am trying to use a ParallaxView to make an image within the GridViewItem parallax as the GridView is scrolled. The intended effect is the same as the newsfeed in the Xbox UWP app on PC; images on the listview items there parallax as you scroll. This is shown visually in the following image:
I am running into a databinding data context issue, however. All of the examples I have seen are to make the background of the entire GridView or ListView parallax. A working example of that is as follows (very similar to the XAML Controls Gallery Sample found here):
<Grid>
<ParallaxView Name="GridViewParallaxView"
Source="{x:Bind MyGridView}"
VerticalShift="100">
<!-- This is the background image that parallaxes. -->
<Image></Image>
</ParallaxView>
<GridView Name="MyGridView">
<!-- GridView Content Here... -->
</GridView>
</Grid>
The problem I am running into is when trying to place the ParallaxView INSIDE of the DataTemplate in the ItemTemplate in the GridView.
<GridView Name="MyGridView"
ItemsSource="{x:Bind MyDataList}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="models:MyDataType">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<ParallaxView Name="GridViewParallaxView"
Grid.Row="0"
Source="{x:Bind MyGridView}"
VerticalShift="100">
<!-- This is the image ON EACH GRIDVIEW ITEM that parallaxes. -->
<Image Source="{x:Bind MySource}"></Image>
</ParallaxView>
<TextBlock Name="ItemTitleTextBlock"
Grid.Row="1"
Text="{x:Bind Title}"></TextBlock>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
Note that some properties (like MinWidth and Margin) have been omitted for brevity.
The code behind (not totally relevant, but to add context to some of the bindings):
public class MyPage : Page
{
public ObservableCollection<MyDataType> MyDataList { get; set; }
}
public class MyDataType
{
public string Title { get; set; }
public ImageSource MySource { get; set; }
}
This does not work because placing the 'ParallaxView' inside of the 'DataTemplate' changes the 'DataContext'. MyGridView can no longer be bound to directly like that. So how do I bind it?
Also, I read that the DataContext property is inherited by children in the XAML tree. I need the Image databinding to be in the same context as the DataTemplate. Is there a way to just change the DataContext for the ParallaxView?
You could use Binding, instead of x:Bind.
<ParallaxView Name="GridViewParallaxView"
Grid.Row="0"
Source="{Binding ElementName=MyGridView}"
VerticalShift="100">
<!-- This is the image ON EACH GRIDVIEW ITEM that parallaxes. -->
<Image Source="{x:Bind MySource}"></Image>
</ParallaxView>

Issues with child page's display when using Frames

Problem
This is the layout of my main pane:
<Page
x:Class="Communities.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Communities"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Loaded="Page_Loaded" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="48" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
...
<SplitView Grid.Row="1" Name="hamburgerMenu" OpenPaneLength="200" PaneBackground="#F02A2A2A">
<SplitView.Pane>
<ListView ItemsSource="{Binding}" IsItemClickEnabled="True" ItemClick="HamburgerItemClick">
... </ListView>
</SplitView.Pane>
<Frame Name="frame" />
</SplitView>
<Grid Grid.RowSpan="3" Name="popupArea" />
</Grid>
</Page>
the frame is where I load all my pages, so that the layout is always consistant.
Now, in most of my child pages I have defined AppBar control and attached it to the BottomAppBar property of that child page:
PostView.xaml
...
<Page.BottomAppBar>
<CommandBar>
<AppBarButton Label="Back" Icon="Back" Click="TryGoBack" />
<AppBarButton Label="Refresh" Icon="Refresh" Click="TryRefreshComments" />
<AppBarButton Label="Go to Community" Icon="Go" Click="TryOpenCommunity" />
</CommandBar>
</Page.BottomAppBar>
...
Here's where the trouble starts. It works fine on PC, as the layout is mostly static on desktop. There are no software keyboards required most of the time etc. On mobile it's more problematic: Screenshots
My thoughts
It seems like the frame that is used to display the child page is causing all sorts of problems. When the AppBar is defined in the main page it positions correctly.
I'd like to avoid the keyboard covering the textbox as well as the AppBar but I don't want to get rid of the frame control. I'd also prefer it if the page got "squished" when the keyboard shows up, instead of getting pushed upwards, but I'm not sure how to display the keyboard on the frame level, instead of the entire MainPage, default level.
What would be the best way to solve this situation?
Cheers!
As you know, if we set the Page.BottomAppBar in the root of the Page, there is no issue with Touch keyboard. It seems it is the best way to add the Page.BottomAppBar.
If you want to add the Page.BottomAppBar in the other page in the Frame, you should be able to customize your UI. The UWP provides similar behavior on the appearance of the touch keyboard by handling the Showing and Hiding events exposed by the InputPane object.
We can use the InputPaneVisibilityEventArgs.OccludedRect to get the region of the application's window that the input pane is covering.
For example:
public PostView()
{
this.InitializeComponent();
InputPane.GetForCurrentView().Showing += PostView_Showing;
InputPane.GetForCurrentView().Hiding += PostView_Hiding;
}
private void PostView_Hiding(InputPane sender, InputPaneVisibilityEventArgs args)
{
MyTextBox.Margin = new Thickness(0, args.OccludedRect.Height, 0, 0);
}
private void PostView_Showing(InputPane sender, InputPaneVisibilityEventArgs args)
{
MyTextBox.Margin = new Thickness(0, 0, 0, args.OccludedRect.Height);
}

Create a component and reuse it in Windows phone 8.1

I want to create some components and reuse them in different pages, put more than one in a page, etc.
For example, I want to create a component that contains an image, some text, etc. The position of the elements are fixed, but I will change the image, the text... I mean, in a same page I want to put three circles with different image and text...
What is the best way to do it? I've found UserControl, but I'm unable to call a method from another page to change something.
This is my component XAML
<UserControl
x:Class="aa.Components.CircularGraph"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Components"
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="300">
<Grid Name="view">
<Image Name="imageGraph" Source="../Assets/aa/circuloGris.png"
/>
<StackPanel Orientation="Vertical">
<TextBlock Name="firstLine" Text="1" FontFamily="Arial" FontSize="9"></TextBlock>
<TextBlock Name="secondLine" Text="2" FontFamily="Arial" FontSize="9"></TextBlock>
<TextBlock Name="thirdLine" Text="3" FontFamily="Arial" FontSize="9"></TextBlock>
</StackPanel>
</Grid>
</UserControl>
Its code:
public sealed partial class CircularGraph: UserControl {
public CircularGraph() {
this.InitializeComponent();
Height = 300;
Width = 400;
}
public void changeFirstLine(string var) {
firstLine.Text = var;
}
}
In other page I put:
<local:CircularGraph Name="circularGraph"/>
And I've tried to put this in .cs:
protected override void OnNavigatedTo(NavigationEventArgs e) {
circularGraph.changeFirstLine("aaa");
}
But I have an error: The name 'circularGraph' does not exits in the current context.
How can I do this?
Sorry if it's a simple question. I'm newbie at Windows phone.
Thank you very much!
Try x:Name instead of Name. "All x:Name means to XAML is generate a field to store the value in the code behind class."
<local:CircularGraph x:Name="circularGraph"/>
In WPF, what are the differences between the x:Name and Name attributes?

How to sort a Listview in a DataTemplate in XAML only?

I have a window with a TabControl that i've bind to a list of objec, I'll called MyItem :
<TabControl Name="MyTabPNL" Background="Gainsboro"
ItemsSource="{Binding MyItemList, ElementName=WatcherWindow}"
ContentTemplate="{StaticResource tabItemTemplate}">
</TabControl>
This MyItem class has an ObservableCollection, that I want to bind to a Listview, I'm doing this with a DataTemplate.
GOAL: I'd like to sort automatically this ObservableCollection in XAML. Usually i would use a CollectionViewSource, but i can't find a way to this... I've tried stuff like that:
<DataTemplate x:Key="tabItemTemplate">
<DataTemplate.Resources>
<CollectionViewSource x:Key='dayList' Source="{Binding MyDayList}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="MyDate" Direction="Descending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</DataTemplate.Resources>
<Grid >
<ListView ItemsSource="{Binding Source={StaticResource dayList}}" >
<ListView.View>
<GridView x:Name="gridvwDay" >
<GridViewColumn Header="MyDate"
CellTemplate="{StaticResource myCellTemplatePNLDate}"
HeaderContainerStyle="{StaticResource CustomHeaderStyleNeutral}"
Width="70" />
</GridView>
</ListView.View>
</ListView>
</Grid>
But everytime i've got the same error:
System.Windows.Data Error: 2 : Cannot
find governing FrameworkElement or
FrameworkContentElement for target
element.
BindingExpression:Path=MyDayList;
DataItem=null; target element is
'CollectionViewSource'
(HashCode=58368655); target property
is 'Source' (type 'Object')
I can't find a way to make a link between the dayList in the ListView ItemsSource, and the dayList in the CollectionRessource.
Do you guys have an idea?
FYI: pre sorting the ObservableCollection is not doable, because of the nature of the Class i'm using.
Have you tried simply,
<ListView ItemsSource="{StaticResource dayList}">
As per the doc: http://msdn.microsoft.com/en-us/library/ms750950.aspx
You don't need to bind when its just static on the page :)