I'm attempting to use the ContinuumNavigationTransition effect in a Windows 10 UWP app. I can get the EntranceElement to correctly fly in when navigating pages, but the ExitElement never animates out.
As a repro case, I made a bare minimum app, with still no success. My code looks like the following:
MainPage.xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center">
<ListView x:Name="TheList"
ContinuumNavigationTransitionInfo.ExitElementContainer="True"
ItemsSource="{x:Bind SomeItems}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"
Style="{StaticResource HeaderTextBlockStyle}"
ContinuumNavigationTransitionInfo.IsExitElement="True"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Navigate"
HorizontalAlignment="Center"
Tapped="Button_Tapped"/>
</StackPanel>
</Grid>
MainPage.xaml.cs
public ObservableCollection<String> SomeItems = new ObservableCollection<string>
{
"Item 1!",
"Item 2!"
};
public MainPage()
{
this.InitializeComponent();
}
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(SubPage));
}
SubPage.xaml
<Page.Transitions>
<TransitionCollection>
<NavigationThemeTransition>
<NavigationThemeTransition.DefaultNavigationTransitionInfo>
<ContinuumNavigationTransitionInfo/>
</NavigationThemeTransition.DefaultNavigationTransitionInfo>
</NavigationThemeTransition>
</TransitionCollection>
</Page.Transitions>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="I'm an entrance element!"
VerticalAlignment="Center"
HorizontalAlignment="Center"
ContinuumNavigationTransitionInfo.IsEntranceElement="True"
TextWrapping="WrapWholeWords"
Style="{StaticResource SubheaderTextBlockStyle}"/>
</Grid>
SubPage.xaml.cs
public SubPage()
{
this.InitializeComponent();
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
SystemNavigationManager.GetForCurrentView().BackRequested += SubPage_BackRequested;
}
private void SubPage_BackRequested(object sender, BackRequestedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(MainPage));
SystemNavigationManager.GetForCurrentView().BackRequested -= SubPage_BackRequested;
}
I believe where you are going wrong is that you are using a button to navigate whereas Entrance elements and exit elements are used to kind of carry the context forward. So ideally you should navigate on listview item click.Code wise I couldn't see anything wrong and check this link it might be of some use.
http://www.visuallylocated.com/post/2014/06/24/Page-transitions-and-animations-in-Windows-Phone-Runtime.aspx
Related
i want to send Data from one Textbox on window One to a label on window Two.
starting with window two:
<StackPanel>
<StackPanel x:Name="ButtonStackPanel" Height="Auto" Width="Auto">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<Button Style="{DynamicResource ButtonStyle}" Content="To The Dark Side" Click="OnClickToDarkSide"/>
<Button Style="{DynamicResource ButtonStyle}" Content="To The Gray" Click="OnClickToGraySide"/>
<Button Style="{DynamicResource ButtonStyle}" Content="To The Light Side" Click="OnClickToLightSide"/>
</StackPanel>
<Border HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="Red" Height="Auto" Width="2"/>
<Label Style="{DynamicResource LabelStyle}" x:Name="theTextBlock" Content="{Binding Source=CodeText}"/>
<Border HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="Red" Height="Auto" Width="2"/>
<ToggleButton Style="{DynamicResource ToggleButtonStyle}" Content="Open Style Window" Name="StyleWindowButton" Click="OnClickOpenStyleWindow"/>
<ToggleButton Style="{DynamicResource ToggleButtonStyle}" Content="Open Text Window" Name="TextWindowButton" Click="OnClickOpenTextWindow"/>
</StackPanel>
<Border Height="2" Width="Auto" Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
</StackPanel>
<Border Height="2" Width="Auto" Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
</StackPanel>
Codebehind of Window Two:
public MainWindow()
{
(App.Current as App).CodeText = _jediCode;
InitializeComponent();
}
private void OnClickToDarkSide(object sender, RoutedEventArgs e)
{
(App.Current as App).ChangeSkin(Skin.Dark);
(App.Current as App).CodeText = _sithCode;
theTextBlock.Content = (App.Current as App).CodeText;
}
private void OnClickToLightSide(object sender, RoutedEventArgs e)
{
(App.Current as App).ChangeSkin(Skin.Light);
(App.Current as App).CodeText = _jediCode;
theTextBlock.Content = (App.Current as App).CodeText;
}
private void OnClickToGraySide(object sender, RoutedEventArgs e)
{
(App.Current as App).ChangeSkin(Skin.Gray);
(App.Current as App).CodeText = _grayCode;
theTextBlock.Content = (App.Current as App).CodeText;
}
private void OnClickOpenStyleWindow(object sender, RoutedEventArgs e)
{
if (StyleWindowButton.IsChecked == true)
{
styleWindow = new StyleWindow();
styleWindow.Show();
}
else
{
styleWindow.Close();
styleWindow = null;
}
}
private void OnClickOpenTextWindow(object sender, RoutedEventArgs e)
{
if (TextWindowButton.IsChecked == true)
{
textWindow = new InputWindow();
textWindow.Show();
}
else
{
textWindow.Close();
textWindow = null;
}
}
}
window one:
<Grid>
<TextBox HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="200" TextWrapping="Wrap"
AcceptsReturn="True" AcceptsTab="True" Text="{Binding Path=CodeText, Source={x:Static Application.Current}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Margin="10,10,0,0">
<!-- TODO: trigger change from this textbox to the textblock in mainwindow -->
</TextBox>
</Grid>
code behind of one is empty.
app.xaml.cs:
public string CodeText
{
get => _codeText;
set { _codeText = value; OnPropertyChanged(nameof(CodeText)); }
}
Ok, the current behavior is clicking on one of the buttons (Dark Side, Gray, Light Side) leads to changes in the CodeText Property, which leads to a change of the content of the label of Window Two and the text of TextBox of Window One. Changing the text of the TextBox, changes also the CodeText Property, but does not lead to a change in the label and thats confusing, why does it work the one way, but not the other.
hope you have a hint for me. :) Maybe i missed a trigger or a kind of refresh for the label
bindings in window One and Two are set differently. (window Two does it wrong, Content="{Binding Source=CodeText}" is not valid binding)
in fact, window Two removes the binding by assigning CodeText directly as local value:
theTextBlock.Content = (App.Current as App).CodeText;
you should remove that line, and use the same binding as in window One:
<Label Style="{DynamicResource LabelStyle}" x:Name="theTextBlock"
Content="{Binding Path=CodeText, Source={x:Static Application.Current}}"/>
I have the following TabControl:
<TabControl Name="tabControl" Grid.Row="0" MinWidth="270" HorizontalAlignment="Stretch" ItemsSource="{Binding Counters}" ContentTemplate="{StaticResource templateForTheContent}"
ItemTemplate="{StaticResource templateForTheHeader}">
</TabControl>
It uses this DataTemplate:
<Window.Resources>
<DataTemplate x:Key="templateForTheContent" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0"
ItemsSource="{Binding}"
SelectionMode="Multiple"
BorderThickness="1" BorderBrush="#FF8B8B8B" SelectionChanged="ListBox_SelectionChanged_1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding CounterName, Mode=OneWay}" />
<Run Text="{Binding InstanceName, Mode=OneWay}" />
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="RAMSelectAllButton" Margin="0,10,0,0" Grid.Column="0" Grid.Row="1">
<TextBlock Text="SELECT ALL"/>
</Button>
<Button Name="RAMUnSelectAllButton" Margin="0,10,0,0" Grid.Column="1" Grid.Row="1">
<TextBlock Text="UNSELECT ALL"/>
</Button>
</Grid>
</DataTemplate>
<DataTemplate x:Key="templateForTheHeader" >
<TextBlock Text="{Binding CategoryName}"/>
</DataTemplate>
</Window.Resources>
It works as expected, binding works well, everything would be totally fine if this issue wasn't present:
Each time I switch a tab in my TabControl, selected items of a ListBox in my previous tab are reset - so when I go back to that tab - nothing is selected.
How to fix this?
//EDIT
here's my ListBox_SelectionChanged_1 method:
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
System.Windows.Controls.ListBox listBoxTemp = sender as System.Windows.Controls.ListBox;
PerformanceCounter counterTemp = (PerformanceCounter)listBoxTemp.Items[0];
if (!appData.SelectedCounters.ContainsKey(counterTemp.CategoryName))
appData.SelectedCounters.Add(counterTemp.CategoryName, new List<PerformanceCounter>());
appData.SelectedCounters[counterTemp.CategoryName].Clear();
foreach (PerformanceCounter counter in listBoxTemp.SelectedItems)
{
appData.SelectedCounters[counterTemp.CategoryName].Add(counter);
}
}
ListBox is bound to Counters, which is Observable Collection:
public ObservableCollection<ObservableCollection<PerformanceCounter>> Counters
{
get { return _Counters; }
}
ObservableCollection<ObservableCollection<PerformanceCounter>> _Counters = new ObservableCollection<ObservableCollection<PerformanceCounter>>();
(i am not familiar with TabControls, or WPF for that matter, but i would suggest a solution like this:)
Backup the selected items of your ListBox in a Dictionary.
var selectionBackups = new Dictionary<ListBox, IEnumerable<ListBoxItem>>();
I'd keep this field updated in ListBox_SelectionChanged_1(). Whenever you enter a Tab, overwrite the concerned ListBox's selection.
void TabEnter(object sender, TabEventArgs e)
{
ListBox lb = ... //acquire the current Listbox
OverwriteSelection(lb, selectionBackups[lb]); //set the ListBox's selection
}
(You might want to prevent the ListBox_SelectionChanged_1() from triggering when you restore the selection. That could be done like this:
bool auto_select = false; //set this to true while editing selections
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
if(auto_select)
return;
...
}
)
I want to open an Edit-page i've created when i click on the MenuFlyoutItem. Heres the code for my ListView:
<ListView Name="ModelListXAML" Grid.Row="1" Margin="0,12,0,0" CanDragItems="True" SelectionChanged="ModelListXAML_SelectionChanged" ItemClick="ModelListXAML_ItemClick">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,5" Holding="ModellItem_Holding">
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Name="ModellMenuEdit" Click="ModellMenuEdit_Click" Text="Bearbeiten"/>
<MenuFlyoutItem x:Name="ModellMenuDelete" Click="ModellMenuDelete_Click" Text="Löschen"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<StackPanel Margin="10, 0,0,0">
<TextBlock Text="{Binding name}" FontFamily="Segoe WP Semibold" FontSize="30" HorizontalAlignment="Left" Grid.Row="0"/>
<TextBlock Text="{Binding captions}" FontFamily="Segoe WP Semibold" FontSize="20" HorizontalAlignment="Left" Grid.Row="1" Foreground="Gray"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
My Problem is, that the app crashes, when the ModellMenuEdit_Click event get's fired. Visual Studio gives me this Error:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
And here's the Code for the ModelMenuEdit_Click event:
private void ModellMenuEdit_Click(object sender, RoutedEventArgs e)
{
Modell datacontext = (e.OriginalSource as FrameworkElement).DataContext as Modell;
Frame.Navigate(typeof(ModellEdit));
}
Any idea how to solve this? Thank's for any response in advance :)
The problem is with the way you're trying to retrieve the DataContext. Try this:
private void ModellMenuEdit_Click(object sender, RoutedEventArgs e)
{
var menuFlyoutItem = sender as MenuFlyoutItem;
Modell datacontext;
if (menuFlyoutItem != null)
{
datacontext = menuFlyoutItem.DataContext as Modell;
}
Frame.Navigate(typeof(ModellEdit), /*in case you want to pass datacontext*/ datacontext);
}
I've solved it! The actual problem was in the OnNavigatedTo() Method for the ModellEdit page :)
I have DataTemplate which I use in HubSection:
<DataTemplate x:Name="dataTemplate2">
<Grid x:Name="greedy">
<ScrollViewer x:Name="scroller" SizeChanged="ScrollViewer_SizeChanged" Height="{Binding Height,ElementName=greedy}" >
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource dataTemplateDetails}">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<ReorderThemeTransition />
<NavigationThemeTransition />
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
</ItemsControl>
</ScrollViewer>
</Grid>
</DataTemplate>
In my ItemsControl I have items which can be expandable. What I want to achieve is that when the item will expand to see more details about that item. I want Scrollviewer to scroll down (for amount of changed size of ScrollViewer).
Code behind for SizeChanged event:
private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
{
ScrollViewer myScroll = (ScrollViewer)sender;
myScroll.ChangeView(null, myScroll.ScrollableHeight, null, false);
}
What I have done now is not working as my expectation. I scroll down to the end right now. But the thing is it scrolls only when the items extend the size of available view (ScrollBar is shown). Then if I expand another item it doesn't work. If I hide details about item (ScrollBar hides too) and expand it again it will work again.
It's like the SizeChanged event occures only when ScrollViewer is going into action but have infinite height which doesn't change.
I've tried Grid with row set to "*", it changes nothing. Now I try to set height by binding it to height of ItemsControl - still the same behaviour.
Could you help me with the solution, show the path of thinking or enlighten me with some workaround?
EDIT:
I prepared some code to work with to see what happens exactly.
1) Create New Project -> Store Apps (c#) -> Windows Phone 8.1 (Blank App) and name it "scroll"
2) Paste this code into MainPage.xaml
<Page
x:Class="scroll.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:scroll"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="DarkOliveGreen">
<Page.Resources>
<DataTemplate x:Name="dataTemplateDetails">
<Grid Name="grido" Grid.Row="1" Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="Auto" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="Black" CornerRadius="10" Opacity="0.4" />
<Border Grid.Row="1" Background="Black" CornerRadius="10" Opacity="0.3" />
<Border Grid.Row="2" Background="Black" CornerRadius="10" Opacity="0.2" />
<Border Grid.Row="3" Background="Black" CornerRadius="10" Opacity="0.1" />
<TextBlock Grid.Row="0" Text="{Binding Name}" Style="{StaticResource BaseTextBlockStyle}" HorizontalAlignment="Center"/>
<Grid Grid.Row="1" HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="5,0,5,0" Text="Description:" Style="{StaticResource BaseTextBlockStyle}"/>
<TextBlock Grid.Column="1" Text="{Binding Description}" Style="{StaticResource BaseTextBlockStyle}"/>
</Grid>
<TextBlock Grid.Row="2" Text="Next row" Style="{StaticResource BaseTextBlockStyle}" HorizontalAlignment="Center"/>
<TextBlock Grid.Row="3" Text="Next row" Style="{StaticResource BaseTextBlockStyle}" HorizontalAlignment="Center"/>
</Grid>
</DataTemplate>
<DataTemplate x:Name="dataTemplate2">
<Grid x:Name="greedy" >
<ScrollViewer x:Name="scroller" SizeChanged="ScrollViewer_SizeChanged" VerticalAlignment="Top">
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource dataTemplateDetails}">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<ReorderThemeTransition />
<NavigationThemeTransition />
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
</ItemsControl>
</ScrollViewer>
</Grid>
</DataTemplate>
</Page.Resources>
<Page.BottomAppBar>
<CommandBar Background="Black" Opacity="0.6" x:Name="myCommandBar">
<AppBarButton Icon="Add" Label="Add" x:Name="AddItem" Click="Add_Click"/>
<AppBarButton Icon="Delete" Label="Delete" x:Name="RemoveItem" Click="Delete_Click"/>
</CommandBar>
</Page.BottomAppBar>
<Grid>
<Hub x:Name="myHub" Header="Test">
<HubSection x:Uid="myDetailsHubsection" x:Name="myDetailsHubsection" Header="Details" DataContext="{Binding Items}" ContentTemplate="{StaticResource dataTemplate2}" />
</Hub>
</Grid>
3) Paste this code into MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace scroll
{
public sealed partial class MainPage : Page
{
public static Details dataContextItems;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
dataContextItems = new Details();
}
public class TestItem
{
public string Name { get; set; }
public string Description { get; set; }
public TestItem(string n, string d)
{
Name = n;
Description = d;
}
}
public class Details : INotifyPropertyChanged
{
private ObservableCollection<TestItem> _items;
public ObservableCollection<TestItem> Items
{
set
{
_items = value;
NotifyPropertyChanged("Items");
}
get
{
return _items;
}
}
public Details()
{
_items = new ObservableCollection<TestItem>();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = dataContextItems;
}
private void Add_Click(object sender, RoutedEventArgs e)
{
TestItem iAmAnItem = new TestItem("Name of an item", "Long and detailed description of an item");
dataContextItems.Items.Add(iAmAnItem);
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
if (dataContextItems.Items.Count > 0)
dataContextItems.Items.RemoveAt(0);
}
private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
{
ScrollViewer myScroll = (ScrollViewer)sender;
myScroll.ChangeView(null, myScroll.ScrollableHeight, null, false);
}
}
}
4) Run the app
5) When you add first two items you can't scroll them but when you add more items you can see that it scrolls down as soon as items "need more space" to be shown and scrollbar occures. But with adding more items it doesn't work. If you delete items and add "third" item again it will scroll down.
I want it to scroll down everytime size of scrollviewer changes (in this case when new item occures but keep in mind it should work when item "extends" in my original solution and there can be few extended items simultaneously).
I've been tinkering with the solution and I finally found a way to do that.
I think the problem is that I didn't understand how ScrollViewer does work. I took the scrolling height as UIElement height hoping for SizeChanged to be fired what isn't truth. ScrollViewer wasn't changing its size because it just took the whole space it could and then just displayed how much content it is in it (It's like ScrollViewer has almost always infinite height unless it's less than actual available view space). With adding first two items SizeChanged event was firing with third one too and then nothing happend. It proves that.
I needed SizeChanged to be fired everytime the size of ScrollViewer (or in this case the Grid) was changing. Solution is very simple but still it needs understanding of how ScrollViewer works - and now it seems so obvious that it will never be greater than available space.
Changes made to make it work:
<DataTemplate x:Name="dataTemplate2">
<ScrollViewer x:Name="scroller" VerticalAlignment="Top" HorizontalAlignment="Stretch" IsEnabled="True" >
<Grid VerticalAlignment="Top" x:Name="greedo" SizeChanged="greedo_SizeChanged">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource dataTemplateDetails}">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<ReorderThemeTransition />
<NavigationThemeTransition />
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
</ItemsControl>
</Grid>
</ScrollViewer>
</DataTemplate>
and code behind:
private void greedo_SizeChanged(object sender, SizeChangedEventArgs e)
{
Grid takingScroll = (Grid)sender;
ScrollViewer myScroll = (ScrollViewer)takingScroll.Parent;
myScroll.ChangeView(null, myScroll.ScrollableHeight, null, false);
}
thats my navigation window
<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="800" Width="600" Source="Page1.xaml">
thats my page1
<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="600" d:DesignWidth="800"
Title="Page1" Name="IndexPage">
<ListView Name="myListView" ItemsSource="{Binding ElementName=IndexPage, Path=SeriesCollection}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" IsSynchronizedWithCurrentItem="True" SelectionChanged="handleSelected">
<ListView.ItemsPanel >
<ItemsPanelTemplate>
<WrapPanel>
</WrapPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel >
<Image Width="214" Height="317" Source="{Binding Image}"/>
<Label Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Page 2 is just en empty skeleton
code behind
namespace WpfApplication1
{
/// <summary>
/// Interaktionslogik für Page1.xaml
/// </summary>
public partial class Page1 : Page
{
private ObservableCollection<Series> _series =
new ObservableCollection<Series>();
public ObservableCollection<Series> SeriesCollection
{
get { return _series; }
}
public Page1()
{
InitializeComponent();
DirectoryInfo baseDir = new DirectoryInfo(#"C:\Serien");
DirectoryInfo[] dirs = baseDir.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
Series serie = new Series(dir);
Console.WriteLine("adding " + serie.Name);
_series.Add(serie);
}
Console.WriteLine(_series.Count);
}
public void handleSelected(object sender, RoutedEventArgs args)
{
Series currentSerie = (Series) myListView.Items.CurrentItem;
Page2 page = new Page2();
this.NavigationService.Navigate(page);
Console.WriteLine(currentSerie.Name);
Console.WriteLine(currentSerie.GetType());
Console.WriteLine(currentSerie.ToString());
}
}
}
so i click on an item to trigger the SelectionChanged Event to handle it in SelectionChanged where i navigate to page2 , so far so good.
then i use the back button from the navigation window and get stuck with an NullpointerException at
this.NavigationService.Navigate(page);
i dont even know why this method is triggered. So obviosly i am doing something stupid. Pls tell me what it is. Thanks for your time and affort.
The problem here is that you handle the wrong event. I assume that you want to open Page2 by clicking a ListViewItem. Therefore you should use mouse events instead of SelectionChanged.
For example, you can subscribe to StackPanel MouseDown event in your DataTemplate:
<DataTemplate>
<StackPanel Background="Transparent"
MouseDown="StackPanel_MouseDown">
<Image Width="214" Height="317" Source="{Binding Image}"/>
<Label Content="{Binding Name}"/>
</StackPanel>
</DataTemplate>
You can access clicked Series using the following:
private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
{
var currentSerie = (Series)((StackPanel)sender).DataContext;
...
}
UPD If you need a real click, you may use a trick like this:
<DataTemplate>
<Button Click="Button_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<ContentPresenter/>
</ControlTemplate>
</Button.Template>
<StackPanel Background="Transparent">
<Image Width="214" Height="317" Source="{Binding Image}"/>
<Label Content="{Binding Name}"/>
</StackPanel>
</Button>
</DataTemplate>
We use a Button like a view-model which is able to handle clicks.