Manipulating Application Bars in Windows Phone 8.1 XAML from Code Behind - c#

This might be a trivial beginner question and I have found quite a bit of related information for Windows and Silverlight apps but nothing that would directly help me. I'm writing a Windows Phone 8.1/WinRT app in C# and XAML, and I would like to programmatically modify application bars created in XAML. For instance, there is a button I want to include in debug builds only, using preprocessor directives in code behind.
In the following XAML code I'm creating a BottomAppBar with two buttons. How can I create the second button (AppBarAddSampleItemsButton) including all properties in code behind?
<prism:VisualStateAwarePage.BottomAppBar>
<CommandBar >
<CommandBar.PrimaryCommands>
<AppBarButton x:Uid="AppBarNewItemButton"
Label="New item"
Icon="Add" Command="{Binding GoToAddItemPageCommand}" />
</CommandBar.PrimaryCommands>
<CommandBar.SecondaryCommands>
<AppBarButton x:Uid="AppBarAddSampleItemsButton"
Label="Add sample items"
Command="{Binding GoToAddSampleItemssPageCommand}" />
</CommandBar.SecondaryCommands>
</CommandBar>
</prism:VisualStateAwarePage.BottomAppBar>

Here is a sample code creating an AppBarButton in the code behind and adding it to BottomAppBar of the current Page:
private void AddButtonToAppBar()
{
AppBarButton buttonToAdd = new AppBarButton { Label = "Label", Icon = new SymbolIcon(Symbol.Help) };
buttonToAdd.Click += async (sender, e) => await new MessageDialog("Button clicked").ShowAsync();
// add button to Page's BottoAppBar
(BottomAppBar as CommandBar).PrimaryCommands.Add(buttonToAdd);
}
Edit - as for Binding (again from the top of my head, so you will have to check this) this should probably work:
Binding myBind = new Binding();
myBind.Path = new PropertyPath("GoToAddSampleItemssPageCommand");
myBind.Source = DataContext;
buttonToAdd.SetBinding(AppBarButton.CommandProperty, myBind);
More about DataBinding at MSDN.

After some digging around on the Windows Phone dev center, I found this page: How to change app bar icon buttons and menu items dynamically for Windows Phone. Hope it helps!

Related

How to use Acrylic Accent in Windows 10 Creators Update?

I can't find any detailed document to use Acrylic Accent (CreateBackdropBrush). I found a post in StackOverflow which is somewhat useful but it doesn't help to get started. So please create a detailed answer to this post so that everyone can learn.
Update:
Microsoft has released an official Acrylic material document
Note:
If anyone doesn't know about Acrylic Accent. Acrylic Accent is the new feature in Windows 10 Creators Update that allows the app background to be Blurred and Transparent.
CREATOR UPDATE
XAML
You need to use a component that you put on the background of your app, let's say a RelativePanel
<RelativePanel Grid.Column="0" Grid.ColumnSpan="2" MinWidth="40" x:Name="MainGrid" SizeChanged="Page_SizeChanged"/>
<RelativePanel Grid.Column="0" Width="{Binding ElementName=MainGrid,Path=Width}" Background="#28000000"/>
<Grid>
<!--Having content here, for example textblock and so on-->
</Grid>
The second RelativePanel is used to set the shadow color above the Blur.
.CS
And then you can use the following code :
private void applyAcrylicAccent(Panel panel)
{
_compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
_hostSprite = _compositor.CreateSpriteVisual();
_hostSprite.Size = new Vector2((float) panel.ActualWidth, (float) panel.ActualHeight);
ElementCompositionPreview.SetElementChildVisual(panel, _hostSprite);
_hostSprite.Brush = _compositor.CreateHostBackdropBrush();
}
Compositor _compositor;
SpriteVisual _hostSprite;
and calling it with applyAcrylicAccent(MainGrid);
You also will need to handle the SizeChanged event :
private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (_hostSprite != null)
_hostSprite.Size = e.NewSize.ToVector2();
}
Of course you will need to be on the Creator Update to run this, the CreateHostBackdropBrush() won't work on a mobile device, or in tablet mode.
Also, consider that the panel or grid that you set with a acrylic color won't be able to display any control (as far I've tested yet). So you need to use your relative panel without any control in it.
Transparent Title bar
The transparency of the title bar could be set using the following code
ApplicationViewTitleBar formattableTitleBar = ApplicationView.GetForCurrentView().TitleBar;
formattableTitleBar.ButtonBackgroundColor = Colors.Transparent;
CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
coreTitleBar.ExtendViewIntoTitleBar = true;
Here a example of what the above code generate (with some other things added too.)
Fall Update 10.0.16190 and above
As Justin XL mention in an answer below, starting from the Build 16190 and above, developers have access to different Acrylic Brushes located at Windows.UI.Xaml.Media (Acrylic API) and the guidelines from Microsoft : Acrylic material guidelines
In the Creators Update Insider Preview 16193 (along with Windows 10 SDK 16190), there's a new AcrylicBrush that you can apply directly onto your element just like a normal SolidColorBrush.
<Page xmlns:media="using:Windows.UI.Xaml.Media" ...>
<Page.Resources>
<media:AcrylicBrush x:Key="HostBackdropBrush"
BackgroundSource="HostBackdrop"
TintColor="LightBlue"
TintOpacity="0.6"
FallbackColor="LightSkyBlue"
FallbackForced="False" />
</Page.Resources>
<Grid Background="{StaticResource HostBackdropBrush}" />
</Page>
Note you can change the BackgroundSource to Backdrop to sample from the app content instead of the content behind the app window. Also make sure you define an appropriate FallbackColor because you will lose the acrylic effect when the app window has lost focus or the device is in battery saver mode.

Review/Checkout page to see selected items. WPF c#

I have a wpf application which helps customers choose a paint colour for their house. Please see image and code below.
code behind
private void REDBUTTONPICKER_Click(object sender, RoutedEventArgs e)
{
var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(#"c:\users\user1\documents\visual studio 2015\Projects\WpfApplication7\paintpicker\RED.jpg", UriKind.Relative));
REDCOLOURPREVIEW.Background = brush;
}
buttons
<Button x:Name="REDBUTTONPICKER" Content="RED" HorizontalAlignment="Left" Height="65" Margin="46,60,0,0" VerticalAlignment="Top" Width="79" Click="REDBUTTONPICKER_Click">
<Button.Background>
<ImageBrush ImageSource="c:\users\user1\documents\visual studio 2015\Projects\WpfApplication7\paintpicker\RED.jpg"/>
</Button.Background>
</Button>
when the customer clicks review I want the colours picked on the previous page to show in the boxes on the "YOUR CHOSEN COLOURS" page. Please see image below.
The four boxes are buttons.
One way of resolving this is to use the MVVM pattern where each of the chosen colors will be bound to properties on the VM. In the selection of the color, it will also set the current unset chosen color to change.
To get an understanding of MVVM I have written a blog article
Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding
which can get you started on creating a basic MVVM architecture to work with.

How to bind textbox in to a mapcontrol in windows phone 8.1

I am trying to develop a map application in windows phone 8.1. In my map there are many locations added with the mapicon. As Map icon is sealed we cannot generate a clickable event. How to add a textbox or a radiobutton in the place of map icon to handle event in order to perform some task. I referred many questions and topics.
<Maps:MapControl x:Name="map1" MapServiceToken="" HorizontalAlignment="Left" Margin="26,57,0,0" VerticalAlignment="Top" Height="306" Width="347">
<Maps:MapItemsControl x:Name="mapitem">
<Maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Maps:MapControl.Location="{Binding }"></TextBox>
</DataTemplate>
</Maps:MapItemsControl.ItemTemplate>
</Maps:MapItemsControl>
</Maps:MapControl>
How to correctly bind this textbox to the map control. So when I click on MapIcon or an XAML control it should be displayed.
In my MapControl their are many locations with MapIcons. So when I click on mapIcon I should get a XAML control. Please suggest me some reference.
This is my code behind file trying to add XAML control
BasicGeoposition bgp = new BasicGeoposition();
RadioButton rd = new RadioButton();
bgp.Latitude = loct.lat;
bgp.Longitude = loct.lng;
Geopoint hwPoint = new Geopoint(bgp);
mapi.Location = hwPoint; //mapi is my mapicon
map1.Children.Add(rd); //map1 is my mapcontrol
When I try to write (map1. ) I cannot find setlocation method
To correctly position your textbox you will need to first need to assign it a location, once that is done you can add it as a child of the map:
MapControl.SetLocation(rd, hwPoint);
MyMap.Children.Add(rd);

WP 8.1 BarButton Icon changing

I'm just starting to learn C# and WP platform and i find it really hard to do some easy things, like changing a button icon, etc.
I've got a Command Bar and a AppBarButton created in XAML.
<Page.BottomAppBar>
<CommandBar MinHeight="60">
<AppBarButton x:Name="Command_BarButton" Icon="AllApps"
Label="Seletie"
Click="AppBar_Select"/>
</CommandBar>
</Page.BottomAppBar>
I would like to change the AppBarButton icon programatically in C# to another prexistent icon, like the Trash icon. How can i do this ?
Command_BarButton.Label = "Delete";
Command_BarButton.Icon = ?
I knew it would be very easy to change the AppBarButton Icon at runtime.
This is how:
Command_BarButton.Label = "Delete";
Command_BarButton.Icon = new SymbolIcon(Symbol.Delete);
Thanks to this link
to change Icon from code behind try this
ApplicationBar = new ApplicationBar();
ApplicationBarIconButton button1 = new ApplicationBarIconButton();
button1.IconUri = new Uri("/Images/play.png", UriKind.Relative);
button1.Text = "play";
ApplicationBar.Buttons.Add(button1);
source
this shuold help
<AppBarButton Label="BitmapIcon" Click="AppBarButton_Click">
<AppBarButton.Icon>
<BitmapIcon UriSource="ms-appx:///Assets/globe.png"/>
</AppBarButton.Icon>
</AppBarButton>
source

Localization of Application Bar in windows phone 8

I want localize my App Bar which I have made in app.xaml but when i try to bind the text of the bar item it says text cannot be empty , i have tried other examples of localized app bar but none of them is working for a app bar which can be used on all pages..
You can declare a global app bar in App.xaml with some fake Text, for example:
<Application
x:Class="PhoneApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
<local:LocalizedStrings xmlns:local="clr-namespace:PhoneApp1" x:Key="LocalizedStrings"/>
<shell:ApplicationBar x:Key="GlobalAppBar">
<shell:ApplicationBarIconButton Text="TEST" IconUri="/Assets/check.png"/>
</shell:ApplicationBar>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
In App.xaml.cs apply localization:
var appBar = App.Current.Resources["GlobalAppBar"] as ApplicationBar;
((ApplicationBarIconButton) appBar.Buttons[0]).Text = AppResources.AppBarButtonText;
Now you can use the global AppBar everywhere in the App, just do initializing in a code behind of a PhoneApplicationPage:
public MainPage()
{
InitializeComponent();
ApplicationBar = App.Current.Resources["GlobalAppBar"] as ApplicationBar;
}
The error you're getting comes from the fact that the ApplicationBar is not a DependencyObject so it doesn't support Bindings. A common alternative is to use custom AppBar with DependencyProperties, most notably BindableApplicationBar..
<bar:BindableApplicationBarButton
Text="{Binding IconButtonText}"
IconUri="{Binding IconUri, FallbackValue=/Icons/Dark/appbar.add.rest.png}"
IsEnabled="{Binding ButtonIsEnabled}" />
or CaliburnBindableAppBar:
<bab:BindableAppBarButton
x:Name="Add"
Text="{Binding AddButtonText}"
Visibility="{Binding ShowAddButton, Converter={StaticResource BooleanToVisibilityConverter}}"
IconUri="{Binding ButtonIconUri}"/>
(.xaml samples from documentations)
Or you could go the way the default VS template suggests:
Add the following code to your page's XAML (they say as the last element, but i'm not sure it matters)
Create a private method in the code behind to add and databind menu items and call it from the constructor (or wherever you're calling InitializeComponent):
XAML:
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Mode="Minimized" />
</phone:PhoneApplicationPage.ApplicationBar>
C# code behind:
private void BuildLocalizedApplicationBar()
{
// Create a new menu item with the localized string from AppResources.
ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AboutMenuItem);
ApplicationBar.MenuItems.Add(appBarMenuItem);
}
Still not an ideal solution, but might be better than referencing non-native components just for such a trivial reason.
A couple of official references a combination of which might be useful as a reference in solving the problem:
How to create an app bar using XAML for Windows Phone - http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394040(v=vs.105).aspx
How to create an app bar using code for Windows Phone - http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff431786(v=vs.105).aspx
How to build a localized app for Windows Phone - http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff637520(v=vs.105).aspx

Categories

Resources