how to set value in text box on button click on other page in uwp? - xaml

In My page right side have some text box (page 1) and in left side some button like 1,2,3(page 2) on text box got focus page 2 come out in frame.
now My problem is that how to set value in text box which is in page 1 on button click which is on page 2 in uwp.

You can use FrameworkElement.FindName method to get the TextBox in your page 1 from your page 2.
For example here:
MainPage has two Frame:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Frame x:Name="frame1"></Frame>
<Frame x:Name="frame2" Grid.Column="1"></Frame>
</Grid>
code behind:
public MainPage()
{
this.InitializeComponent();
this.frame1.Navigate(typeof(MenuPage));
this.frame2.Navigate(typeof(Page1));
}
MenuPage is a blank page here in my test.
Page 1:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Tapped="Grid_Tapped">
<TextBlock Name="textBlock" Text="This is Page 1" VerticalAlignment="Top" FontSize="25" />
<Button VerticalAlignment="Top" Width="1"></Button>
<StackPanel VerticalAlignment="Center">
<TextBox Name="tb1" GotFocus="tb_GotFocus" />
<TextBox Name="tb2" Margin="0,30" GotFocus="tb_GotFocus" />
<TextBox Name="tb3" GotFocus="tb_GotFocus" />
</StackPanel>
</Grid>
code behind:
public Page1()
{
this.InitializeComponent();
this.Loaded += Page1_Loaded;
}
private Frame frame;
private void Page1_Loaded(object sender, RoutedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
Page mainPage = rootFrame.Content as MainPage;
frame = mainPage.FindName("frame1") as Frame;
}
private void tb_GotFocus(object sender, RoutedEventArgs e)
{
frame.Navigate(typeof(Page2));
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
if (frame.CanGoBack)
frame.GoBack();
}
Page 2:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="This is Page 2" VerticalAlignment="Top" FontSize="25" />
<StackPanel VerticalAlignment="Center">
<Button Content="Button 1" Click="Button_Click_1" />
<Button Content="Button 2" Click="Button_Click_2" Margin="0,30" />
<Button Content="Button 3" Click="Button_Click_3" />
</StackPanel>
</Grid>
code behind:
public Page2()
{
this.InitializeComponent();
this.Loaded += Page2_Loaded;
}
private TextBox tb1;
private TextBox tb2;
private TextBox tb3;
private void Page2_Loaded(object sender, RoutedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
Page mainPage = rootFrame.Content as MainPage;
Frame frame = mainPage.FindName("frame2") as Frame;
Page page1 = frame.Content as Page1;
tb1 = page1.FindName("tb1") as TextBox;
tb2 = page1.FindName("tb2") as TextBox;
tb3 = page1.FindName("tb3") as TextBox;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
tb1.Text = "Button 1 Clicked!";
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
tb2.Text = "Button 2 Clicked!";
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
tb3.Text = "Button 3 Clicked!";
}
Rendering Image:
Update:
MainPage calls Page 1:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="Navigate to Page 1" Click="Button_Click" />
</Grid>
code behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(Page1));
}
Page 1 has a Frame and calls Page 2:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Frame Name="myframe"></Frame>
<Grid Grid.Column="1">
<TextBlock Name="textBlock" Text="This is Page 1" VerticalAlignment="Top" FontSize="25" />
<Button VerticalAlignment="Top" Width="1"></Button>
<StackPanel VerticalAlignment="Center">
<TextBox Name="tb1" GotFocus="tb_GotFocus" />
<TextBox Name="tb2" Margin="0,30" GotFocus="tb_GotFocus" />
<TextBox Name="tb3" GotFocus="tb_GotFocus" />
</StackPanel>
</Grid>
</Grid>
code behind:
private void tb_GotFocus(object sender, RoutedEventArgs e)
{
myframe.Navigate(typeof(Page2));
}
Page 2:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="This is Page 2" VerticalAlignment="Top" FontSize="25" />
<StackPanel VerticalAlignment="Center">
<Button Content="Button 1" Click="Button_Click_1" />
<Button Content="Button 2" Click="Button_Click_2" Margin="0,30" />
<Button Content="Button 3" Click="Button_Click_3" />
</StackPanel>
</Grid>
code behind is a little different:
public Page2()
{
this.InitializeComponent();
this.Loaded += Page2_Loaded;
}
private TextBox tb1;
private TextBox tb2;
private TextBox tb3;
private void Page2_Loaded(object sender, RoutedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
Page page1 = rootFrame.Content as Page1;
tb1 = page1.FindName("tb1") as TextBox;
tb2 = page1.FindName("tb2") as TextBox;
tb3 = page1.FindName("tb3") as TextBox;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
tb1.Text = "Button 1 Clicked!";
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
tb2.Text = "Button 2 Clicked!";
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
tb3.Text = "Button 3 Clicked!";
}

Here is the solution I found. It was a combination of part of above. The ShellPage was a frame page. It had a textblock and this code was in the app.xaml.cs page.
ShellPage currentPage = Window.Current.Content as ShellPage;
TextBlock tb1 = currentPage.FindName("InternetConnection") as TextBlock;
tb1.Text = InternetConnectionText;
tb1.Foreground = InternetConnectionForeground;

Related

Bind a click event to a dynamically generated button element in a templated control / template control

I have a templated control in my UWP application which contains a ListView. The ListView is populated in the runtime.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Renderer"
xmlns:triggers="using:Microsoft.Toolkit.Uwp.UI.Triggers">
<Style x:Key="RendererDefaultStyle" TargetType="local:Renderer" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:Renderer">
<Grid>
....
<ListView x:Name="AnnotsList" Margin="0,12,0,0" SelectionMode="None" Grid.Row="1" VerticalAlignment="Stretch" IsItemClickEnabled="True" Visibility="{Binding IsAnnotationsListOpen, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ItemContainerStyle="{StaticResource AnnotationsListViewItemStyle}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding}" />
<TextBlock Text="{Binding DisplayTitle}" Margin="20,0,0,10" FontSize="12" TextWrapping="WrapWholeWords" Visibility="Visible" />
</StackPanel>
<CommandBar Grid.Column="1">
<CommandBar.SecondaryCommands>
<AppBarElementContainer>
<StackPanel Orientation="Horizontal">
<Button x:Name="btn_RemoveFromList" DataContext="{Binding}">
<Button.Content>
<SymbolIcon Symbol="Delete" />
</Button.Content>
<ToolTipService.ToolTip>
<ToolTip Content="Delete" Placement="Mouse" />
</ToolTipService.ToolTip>
</Button>
</StackPanel>
</AppBarElementContainer>
</CommandBar.SecondaryCommands>
</CommandBar>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle >
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Border AutomationProperties.Name="{Binding Key}">
<TextBlock Text="{Binding Key}" Style="{ThemeResource TitleTextBlockStyle}"/>
</Border>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
....
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="local:Renderer" BasedOn="{StaticResource RendererDefaultStyle}"/>
</ResourceDictionary>
I tried to bind a click event to the button like this but since it is dynamically generated it doesn't work.
public sealed class Renderer: Control, IDisposable
{
....
private void UpdateAnnotationsListView()
{
(GetTemplateChild("AnnotsList") as ListView).ItemsSource = null;
var source = AnnotationAdapter.GetGroupedAnnotations(); // ObservableCollection<ListViewGroupInfo>
var viewSource = new CollectionViewSource
{
IsSourceGrouped = true, Source = source
};
(GetTemplateChild("AnnotsList") as ListView).ItemsSource = viewSource.View;
if (viewSource.View.Count > 0)
{
(GetTemplateChild("btn_RemoveFromList") as Button).Click -= null;
(GetTemplateChild("btn_RemoveFromList") as Button).Click += async delegate(object sender, RoutedEventArgs e)
{
await OpenRemoveConfirmationAsync();
};
}
}
....
}
List source is a ObservableCollection of type
public class ListViewGroupInfo: List < object >
{
public ListViewGroupInfo() {}
public ListViewGroupInfo(IEnumerable < object > items): base(items) {}
public object Key
{
get;
set;
}
}
List source is structured in such a way where I can group the list items accordingly.
This is a sample of the rendered ListView for more context.
The Delete buttons are the ones I'm trying to work with here.
I want to bind a method to the click event of those buttons in the ListView.
I Cannot use the name attribute since there can be multiple buttons as the list grows.
Since this button is in a templated control & generated in the runtime, I couldn't find a way to bind a method to the click event.
My guess is that I will have to bind a command to the button. But I couldn't find a way to do that either.
I did not use MVVM pattern in the templated control.
Could anyone help me with this? Any help is much appreciated.
My guess is that I will have to bind a command to the button. But I couldn't find a way to do that either.
The better way is using command to approach, I will share the detail steps below that you could refer to. please note you need to set current page datacontext as this this.DataContext = this;. it could make sure you can access command where in the code behind from DataTemplate.
Xaml Code
<Grid>
<ListView x:Name="MyListView" ItemsSource="{x:Bind Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Header}" />
<TextBlock
Margin="20,0,0,10"
FontSize="12"
Text="{Binding DisplayTitle}"
TextWrapping="WrapWholeWords"
Visibility="Visible" />
</StackPanel>
<CommandBar Grid.Column="1">
<CommandBar.SecondaryCommands>
<AppBarElementContainer>
<StackPanel Orientation="Horizontal">
<Button
x:Name="btn_RemoveFromList"
Command="{Binding DataContext.DeleteCommand, ElementName=MyListView}"
CommandParameter="{Binding}">
<Button.Content>
<SymbolIcon Symbol="Delete" />
</Button.Content>
<ToolTipService.ToolTip>
<ToolTip Content="Delete" Placement="Mouse" />
</ToolTipService.ToolTip>
</Button>
</StackPanel>
</AppBarElementContainer>
</CommandBar.SecondaryCommands>
</CommandBar>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Code behind
public sealed partial class ListPage : Page
{
public ListPage()
{
this.InitializeComponent();
this.DataContext = this;
}
private ObservableCollection<Model> Items { set; get; }
public ICommand DeleteCommand
{
get
{
return new CommadEventHandler<Model>((s) =>
{
Items.Remove(s);
});
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
MakeDataSource();
}
private void MakeDataSource()
{
Items = new ObservableCollection<Model>();
for (int i = 0; i < 10; i++)
{
Items.Add(new Model()
{
Header = $"header{i}",
DisplayTitle= $"DisplayTitle{i}"
});
}
}
}
public class Model
{
public string Header { get; set; }
public string DisplayTitle { get; set; }
}
class CommadEventHandler<T> : ICommand
{
public event EventHandler CanExecuteChanged;
public Action<T> action;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.action((T)parameter);
}
public CommadEventHandler(Action<T> action)
{
this.action = action;
}
}
After a whole bunch of research & trial and error, I ended up with a different approach as #nico-zhu-msft suggested.
Basically, I moved the ListView to a separate user control & observed property changes from the parent template control. In order to bind data to the ListView used a view-model.
AssnotationsList.xaml
<UserControl
x:Class="PDF.Renderer.AnnotationsList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:PDF.Renderer"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodels="using:PDF.Renderer.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.DataContext>
<viewmodels:AnnotationsListViewModel />
</UserControl.DataContext>
<UserControl.Resources>
<Style x:Key="AnnotationsListViewItemStyle" TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</UserControl.Resources>
<ListView SelectionMode="None" VerticalAlignment="Stretch" IsItemClickEnabled="True" ItemContainerStyle="{StaticResource AnnotationsListViewItemStyle}" ItemsSource="{Binding AnnotationsList}" ItemClick="AnnotationListViewItemClick">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding}" />
<TextBlock Text="{Binding DisplayTitle}" Margin="20,0,0,10" FontSize="12" TextWrapping="WrapWholeWords" Visibility="Visible" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle >
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Border AutomationProperties.Name="{Binding Key}">
<TextBlock Text="{Binding Key}" Style="{ThemeResource TitleTextBlockStyle}"/>
</Border>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
</UserControl>
AnnotationsList.xaml.cs
public sealed partial class AnnotationsList : UserControl, INotifyPropertyChanged
{
public AnnotationsList()
{
this.InitializeComponent();
}
private BaseAnnotation selectedAnnotation = null;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public ICollectionView AnnotationsListSource
{
get { return (ICollectionView)GetValue(AnnotationsListSourceProperty); }
set { SetValue(AnnotationsListSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AnnotationsListSourceProperty =
DependencyProperty.Register(nameof(AnnotationsListSourceProperty), typeof(ICollectionView), typeof(AnnotationsList), new PropertyMetadata(null, new PropertyChangedCallback(OnAnnotationsListSourceChanged)));
private static void OnAnnotationsListSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (object.Equals(e.NewValue, e.OldValue) || e.NewValue is null)
return;
d.RegisterPropertyChangedCallback(AnnotationsListSourceProperty, CaptureAnnotationListSource);
}
private static void CaptureAnnotationListSource(DependencyObject sender, DependencyProperty dp) => (sender as AnnotationsList).SetAnnotationsListSource(sender.GetValue(dp) as ICollectionView);
private void SetAnnotationsListSource(ICollectionView annotationsCollection) => (this.DataContext as AnnotationsListViewModel).AnnotationsList = annotationsCollection;
public BaseAnnotation SelectedAnnotation
{
get { return selectedAnnotation; }
set { if (value != selectedAnnotation && value != null) { selectedAnnotation = value; OnPropertyChanged(nameof(SelectedAnnotation)); }; }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedAnnotationProperty =
DependencyProperty.Register(nameof(SelectedAnnotationProperty), typeof(BaseAnnotation), typeof(AnnotationsList), new PropertyMetadata(null));
private void AnnotationListViewItemClick(object sender, ItemClickEventArgs e) => SelectedAnnotation = e.ClickedItem as BaseAnnotation;
}
AnnotationsListViewModel.cs
class AnnotationsListViewModel : ViewModalBase
{
private ICollectionView annotationsList = null;
public ICollectionView AnnotationsList
{
get { return annotationsList; }
set { if(value != annotationsList) { annotationsList = value; OnPropertyChanged(nameof(AnnotationsList)); } }
}
}
Replaced the ListView with the user control Renderer.cs like this.
<local:AnnotationsList x:Name="ctrl_AnnotationsList" Margin="0,12,0,0" Grid.Row="1" VerticalAlignment="Stretch" Visibility="{Binding IsAnnotationsListOpen, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />
In the parent control class Renderer.cs (template control) got a reference to the AnnotationsList control like this when parent is first rendered & bound the PropertyChanged event.
AnnotationsList = GetTemplateChild("ctrl_AnnotationsList") as AnnotationsList;
AnnotationsList.PropertyChanged -= null;
AnnotationsList.PropertyChanged += OnAnnotationsListPropertyChanged;
Added the following code to trigger on property changes in the AnnotationsList control.
private void OnAnnotationsListPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch(e.PropertyName)
{
case "SelectedAnnotation":
var annotation = (sender as AnnotationsList).SelectedAnnotation;
if (annotation != null)
GoToAnnotation(annotation).GetAwaiter();
break;
default:
break;
}
}
For now it is configured to trigger on ItemClick event of the ListViewItems.
Hope this helps someone who might be looking for a similar solution.

How to hide top part of hamburger menu in the XAML Navigation Sample?

In the Windows UWP XAML Navigation sample from git hub, how can you hide the very top part of the hamburger menu flyout that obscures the section title?
Currently it renders like this so there is a strip that hides the section title of the page.
How can I get it to look like this? So the Section title is not obscured when I open the menu.
I tried playing with the z-index of the page header, but it had no effect. The hamburger menu always renders over top everything else.
Just check the Microsoft weather app for windows 10, I think it's more like there is a region out of the SplitView control, which is to hold like "hamburger button", "back button", "commandbar", and "AutoSuggestBox".
Here I wrote a sample:
<Page.Resources>
<local:BoolToVisiableConverter x:Key="visiblecvt" />
<local:BackgroundConverter x:Key="backgroundcvt" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="15*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="{Binding ElementName=listmenu, Path=SelectedItem.MenuText, Converter={StaticResource backgroundcvt}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="50" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Button BorderThickness="0" Background="LightBlue" Click="Button_Click_Pane" Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Button.Content>
<TextBlock Text="" FontFamily="Segoe MDL2 Assets" FontSize="24" />
</Button.Content>
</Button>
<Button BorderThickness="0" Background="Transparent" Click="Button_Click_Back" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Button.Content>
<TextBlock Text="" FontFamily="Segoe MDL2 Assets" FontSize="24" />
</Button.Content>
</Button>
<TextBlock FontSize="24" Grid.Column="2" x:Name="title" VerticalAlignment="Center" Text="{Binding ElementName=listmenu, Path=SelectedItem.MenuText}" />
<CommandBar Grid.Column="3" Background="Transparent" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Visibility="{Binding ElementName=title, Path=Text, Converter={StaticResource visiblecvt}}">
<CommandBar.Content>
<Grid />
</CommandBar.Content>
<AppBarButton Icon="Accept" FontSize="24" Label="Accept" />
<AppBarButton Icon="Cancel" FontSize="24" Label="Cancel" />
</CommandBar>
<AutoSuggestBox Grid.Column="4" VerticalAlignment="Center" HorizontalAlignment="Stretch" IsSuggestionListOpen="True" />
</Grid>
<SplitView Grid.Row="1" x:Name="RootSpiltView" OpenPaneLength="300" CompactPaneLength="50" DisplayMode="CompactOverlay">
<SplitView.Pane>
<ListView x:Name="listmenu" ItemsSource="{x:Bind menu}" SelectionChanged="ListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding MenuIcon}" FontFamily="Segoe MDL2 Assets" FontSize="24" VerticalAlignment="Center" />
<TextBlock Text="{Binding MenuText}" Margin="15" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</SplitView.Pane>
<SplitView.Content>
<Frame x:Name="splitviewContent" Navigated="splitviewContent_Navigated" />
</SplitView.Content>
</SplitView>
</Grid>
code behind:
private ObservableCollection<NavigationItem> menu = new ObservableCollection<NavigationItem>();
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
menu.Clear();
menu.Add(new NavigationItem { PageLink = typeof(Page1), MenuText = typeof(Page1).Name, MenuIcon = "\xE715" });
menu.Add(new NavigationItem { PageLink = typeof(Page2), MenuText = typeof(Page2).Name, MenuIcon = "\xE716" });
menu.Add(new NavigationItem { PageLink = typeof(Page3), MenuText = typeof(Page3).Name, MenuIcon = "\xE722" });
menu.Add(new NavigationItem { PageLink = typeof(Page4), MenuText = typeof(Page4).Name, MenuIcon = "\xE72D" });
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
listmenu.SelectedIndex = 0;
}
private void Button_Click_Pane(object sender, RoutedEventArgs e)
{
this.RootSpiltView.IsPaneOpen = !this.RootSpiltView.IsPaneOpen;
}
private void Button_Click_Back(object sender, RoutedEventArgs e)
{
if (splitviewContent.CanGoBack)
{
splitviewContent.GoBack();
}
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var naviitem = listmenu.SelectedItem as NavigationItem;
splitviewContent.Navigate(naviitem.PageLink);
}
private void splitviewContent_Navigated(object sender, NavigationEventArgs e)
{
var page = splitviewContent.CurrentSourcePageType.Name;
switch (page)
{
case "Page1":
listmenu.SelectedIndex = 0;
break;
case "Page2":
listmenu.SelectedIndex = 1;
break;
case "Page3":
listmenu.SelectedIndex = 2;
break;
case "Page4":
listmenu.SelectedIndex = 3;
break;
}
}
The NavigationItem class and two converters:
public class NavigationItem
{
public string MenuIcon { get; set; }
public string MenuText { get; set; }
public Type PageLink { get; set; }
}
public class BoolToVisiableConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var text = (string)value;
if (text == "Page1")
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
public class BackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var text = (string)value;
if (text == "Page1")
{
return "#FFFFC0CB";
}
return "#00000000";
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
I didn't follow to the official XAML Navigation sample to wrote this code, here my sample renders like this:
#Henk Holterman's comment also makes sense. In the official sample, the title is part of the page content. For different page, the title may have different size. But in Weather app, the title is separated from the content, so it will be easy to achieve.

Xaml simple storyboard/animation

I have a Xaml-view containing three buttons and three usercontrols.
I in the code-behind i have buttons that toggles visibility on or off:
<Grid HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top">
<Button Content="Summer" Click="ButtonBase_OnClick" HorizontalAlignment="Left"/>
<Button Content="Winter" Click="ButtonBase_OnClick3" HorizontalAlignment="Center"/>
<Button Content="Autumn" Click="ButtonBase_OnClick1" HorizontalAlignment="Right"/>
</StackPanel>
<Grid VerticalAlignment="top" HorizontalAlignment="Center" Margin="0,50,0,0">
<StackPanel Width="600" VerticalAlignment="top" Background="LightGreen">
<local:Summer x:Name="Summer" Width="600"></local:Summer>
<local:Winter x:Name="Winter" Visibility="Collapsed" Width="600"></local:Winter>
<local:Autumn x:Name="Autumn" Visibility="Collapsed" Width="600"></local:Autumn>
</StackPanel>
</Grid>
</Grid>
Code behind:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Autumn.Visibility = Visibility.Collapsed;
Summer.Visibility = Visibility.Collapsed;
Winter.Visibility = Visibility.Visible;
}
private void ButtonBase_OnClick1(object sender, RoutedEventArgs e)
{
Autumn.Visibility = Visibility.Collapsed;
Summer.Visibility = Visibility.Visible;
Winter.Visibility = Visibility.Collapsed;
}
private void ButtonBase_OnClick3(object sender, RoutedEventArgs e)
{
Autumn.Visibility = Visibility.Visible;
Summer.Visibility = Visibility.Collapsed;
Winter.Visibility = Visibility.Collapsed;
}
I would like to know how to accomplish a simple animation (slide in) by using storyboards or other way. I´ve seen examples online but I have had a hard time making them work in my specifik case.

Windows phone keyboard display

Is there a way to configure how Windows phone keyboard being displayed?
I have a listview with each item has a TextBox.
When I click on a TextBox, the keyboard will display, and the Textbox (which causes the keyboard) to pop up will be anchored on top of the keyboard.
For example, if I click on the Textbox second last from the end of the list, when the keyboard pop up, the 2nd last TextBox will anchored on top of the keyboard and the keyboard will cover the last Textbox .
Is there anyway to change this behavior?
**XAML**
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,0,0,0">
<TextBlock x:Name="PageTitle" Text="sign in" Margin="0,0,0,0" Height="125" Style="{StaticResource PhoneTextTitle1Style}" Tap="PageTitle_Tap"/>
</StackPanel>
<ScrollViewer Grid.Row="1" x:Name="Scroller" VerticalAlignment="Top">
<Grid x:Name="ContentPanel" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Name="EnterUserIdTitle" Margin="24,0,14,6" FontSize="26" Text="Username"/>
<TextBox Grid.Row="1" Name="EnterUserIdInput" Margin="12,0,24,6" Text="" GotFocus="EnterUserIdInput_GotFocus" LostFocus="UserIdLostFocus" />
<TextBlock Grid.Row="2" Name="EnterPwdTitle" Margin="24,0,14,6" FontSize="26" Text="Password"/>
<PasswordBox Grid.Row="3" Name="EnterPwdInput" Margin="12,0,24,6" GotFocus="EnterPwdInput_GotFocus" LostFocus="EnterPwdInput_LostFocus"/>
<TextBlock Grid.Row="4" Name="ServerUrlTitle" Margin="24,10,24,6" FontSize="26" Text="namespace"/>
<TextBox Grid.Row="5" Name="ServerUrlInput" Margin="12,0,24,6" Text="" TextWrapping="Wrap" GotFocus="ServerUrlInput_GotFocus" LostFocus="ServerUrlInput_LostFocus"/>
<Grid Grid.Row="6" Name="DebugEndPointGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Name="DebugEndpointTitle" Margin="24,10,24,6" FontSize="26" Text="End Point"/>
<TextBox Grid.Row="1" Name="DebugEndpoint" Height="72" Margin="12,0,24,6" GotFocus="DebugEndpoint_GotFocus" LostFocus="DebugEndpoint_LostFocus" />
</Grid>
<CheckBox Grid.Row="7" Name="RemeberCheckbox" Margin="12,0,24,6" Content="Remember Me" IsChecked="True"/>
</Grid>
</ScrollViewer>
</Grid>
----------
**C#**
public partial class MainPage : PhoneApplicationPage
{
public const string SettingsPageUri = #"/SettingsPage.xaml";
private double DefaultScrollerHeight;
private int SIPVisibleScrollerHeight = 250;
private int UserIDOffset = 0;
private int PasswordOffset = 110;
private int ServiceUrlOffset = 250;
private int DebugOffset = 300;
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(SettingsPage_Loaded);
}
private void SettingsPage_Loaded(object sender, RoutedEventArgs e)
{
// Code to avoid screen from pushing upward on launch of SIP and provides options to resize the scroller and remove elastic effect from forms by enabling scrollers when SIP is activated.
// Header also does not push up when textbox gets focus.
//(App.Current as App).RootFrame.RenderTransform = new CompositeTransform();
DefaultScrollerHeight = this.Scroller.Height;
EnterUserIdInput.Tag = false;
EnterPwdInput.Tag = false;
ServerUrlInput.Tag = false;
DebugEndpoint.Tag = false;
}
private void EnterUserIdInput_GotFocus(object sender, RoutedEventArgs e)
{
EnterUserIdInput.Tag = true;
if (this.Scroller.Height != SIPVisibleScrollerHeight)
{
this.Scroller.Height = SIPVisibleScrollerHeight;
this.Scroller.UpdateLayout();
this.Scroller.ScrollToVerticalOffset(UserIDOffset);
}
}
private void UserIdLostFocus(object sender, RoutedEventArgs e)
{
EnterUserIdInput.Tag = false;
}
private void EnterPwdInput_GotFocus(object sender, RoutedEventArgs e)
{
EnterPwdInput.Tag = true;
if (this.Scroller.Height != SIPVisibleScrollerHeight)
{
this.Scroller.Height = SIPVisibleScrollerHeight;
this.Scroller.UpdateLayout();
this.Scroller.ScrollToVerticalOffset(PasswordOffset);
}
}
private void EnterPwdInput_LostFocus(object sender, RoutedEventArgs e)
{
EnterPwdInput.Tag = false;
}
private void ServerUrlInput_GotFocus(object sender, RoutedEventArgs e)
{
ServerUrlInput.Tag = true;
if (this.Scroller.Height != SIPVisibleScrollerHeight)
{
this.Scroller.Height = SIPVisibleScrollerHeight;
this.Scroller.UpdateLayout();
this.Scroller.ScrollToVerticalOffset(ServiceUrlOffset);
}
}
private void ServerUrlInput_LostFocus(object sender, RoutedEventArgs e)
{
ServerUrlInput.Tag = false;
}
private void DebugEndpoint_GotFocus(object sender, RoutedEventArgs e)
{
DebugEndpoint.Tag = true;
if (this.Scroller.Height != SIPVisibleScrollerHeight)
{
this.Scroller.Height = SIPVisibleScrollerHeight;
this.Scroller.UpdateLayout();
this.Scroller.ScrollToVerticalOffset(DebugOffset);
}
}
private void DebugEndpoint_LostFocus(object sender, RoutedEventArgs e)
{
DebugEndpoint.Tag = false;
}
private void SettingsPage_GotFocus(object sender, RoutedEventArgs e)
{
if (!((bool)EnterUserIdInput.Tag) && !((bool)EnterPwdInput.Tag) && !((bool)ServerUrlInput.Tag) && !((bool)DebugEndpoint.Tag))
{
this.Scroller.Height = DefaultScrollerHeight;
this.Scroller.UpdateLayout();
}
}
private void PageTitle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
this.Scroller.Height = DefaultScrollerHeight;
this.Scroller.UpdateLayout();
}
}

Placing PopUp, which is inside a Itemscontrol

I've got an itemscontrol, in which all my elements are PopUps. The problem is I do not know how to place them compared to the grid in which the itemscontrol is placed. I've tried using horizontal- and vertical alignment but this does not help. The xaml code I've got so far is:
<Grid>
<ItemsControl Grid.Row="1" VerticalContentAlignment="Top" HorizontalAlignment="Left" ItemsSource="{Binding PopUp}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ViewModel:PopUpTemplateSelector.EndTurnMenuTemplate>
<DataTemplate>
<Popup IsOpen="{Binding PU.IsOpen}" HorizontalAlignment="Left" VerticalAlignment="Top">
<Design:InGame_NextTurn_UserControl/>
</Popup>
</DataTemplate>
</ViewModel:PopUpTemplateSelector.EndTurnMenuTemplate>
</ViewModel:PopUpTemplateSelector>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
I would suggest maybe using the following overlay method instead.
From this Nokia page:
Overlay XMAL:
<UserControl x:Class="WindowsPhoneSample7.OverLay"
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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
d:DesignHeight="800" d:DesignWidth="480">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="400"/>
<RowDefinition Height="400"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="1">
<ProgressBar IsIndeterminate="True" Foreground="Orange" Height="50" Width="480" VerticalAlignment="Center"/>
<TextBlock Text="Wait" Foreground="Orange" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
</UserControl>
Overlay code-behind:
public OverLay()
{
InitializeComponent();
this.LayoutRoot.Height = Application.Current.Host.Content.ActualHeight;
this.LayoutRoot.Width = Application.Current.Host.Content.ActualWidth;
SystemTray.IsVisible = false; //to hide system tray
}
MainPage code-behind:
public partial class MainPage : PhoneApplicationPage
{
private Popup popup;
// Constructor
public MainPage()
{
InitializeComponent();
this.popup = new Popup();
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
this.LayoutRoot.Opacity = 0.2;
OverLay ovr = new OverLay();
this.popup.Child = ovr;
this.popup.IsOpen = true;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, a) =>
{
Thread.Sleep(5000);
};
worker.RunWorkerCompleted += (s, a) =>
{
popup.IsOpen = false;
this.LayoutRoot.Opacity = 1.0;
};
worker.RunWorkerAsync();
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
this.popup.IsOpen = false;
}
}