Create Application bar dynamically - cross-platform

I want to create Application Bar dynamically in Windows Phone 8. I have used the following code to create application bar in appbar.cs file
class AppBar
{
public AppBar()
{
ApplicationBar appbar;
this.appbar = new ApplicationBar();
this.appbar.IsVisible = true;
this.appbar.Opacity = 1;
this.appbar.Mode = ApplicationBarMode.Minimized;
ApplicationBarIconButton appButon = new ApplicationBarIconButton();
appButon.IconUri = new Uri("/images/show.png", UriKind.Relative);
appButon.Text = "Show";
this.appbar.Buttons.Add(appButon);
appButon.Click += appButon_Click;
}
}
void appButon_Click(object sender, EventArgs e)
{
}
}
If i have created the instance of AppBar class, then all the methods called but i unable to see the application bar. I have given request to create the appbar from webview. From the javainterface i have created the instance of application bar with the given text and icon. How to show this in the web page.

I have solved the my Application bar issue. Added my application bar with parent element(PhoneApplicationPage).
class AppBar
{
public AppBar()
{
ApplicationBar appbar;
PhoneApplicationPage parentpage = (Application.Current.RootVisual as ContentControl).Content as PhoneApplicationPage;
parentpage.ApplicationBar = new ApplicationBar();
appbar = parentpage.ApplicationBar;
appbar.IsVisible = true;
appbar.Opacity = 1;
appbar.Mode = ApplicationBarMode.Minimized;
ApplicationBarIconButton appButon = new ApplicationBarIconButton();
appButon.IconUri = new Uri("/images/show.png", UriKind.Relative);
appButon.Text = "Show";
appbar.Buttons.Add(appButon);
appButon.Click += appButon_Click;
}
}
void appButon_Click(object sender, EventArgs e)
{
}
}

Related

How to add a list of UIelement in Windows Phone

I want to create a page with dynamic control in windows phone.
While doing this I also want to show a progress bar
Below is my code
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
progressstackPanel.Visibility = Visibility.Visible;//progress bar
formScreen = this;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (!isfst)
{
DrawScreen();
}
else
{
//xTitlePanel is only stack panel in my xaml with vertical orientation
xTitlePanel.UpdateLayout();
}
isfst = true;
progressstackPanel.Visibility = Visibility.Collapsed;
});
}
//Code of DrawScreen which is adding control to my stack panels
private void DrawScreen()
{
if (frm_getset.ChildList != null)
{
String[] arr = frm_getset.ChildList.Split(',');
xTitlePanel.Children.Clear();
PrepareControls prepcontrol = new PrepareControls();
foreach (AttributeGetSet a in _Attribute)
{
//this will return a stackpanel containing
// button/textbox etc.depending on a
StackPanel sp = prepcontrol.getControl(i, a.Label, a, formScreen);
try
{
xTitlePanel.Children.Add(sp);
///Here I get a eception only one control is added first one
/// for anyone it is getting a exception Argument
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
i += 1;
}
The system is adding only one control and when ever it try to execute xTitlePanel.Children.Add(sp); it will get an exception.
I solved the problem ,"xTitlePanel" is a StackPanel I created in my XAML. I found you can not add more that one element from Dispatcher to a control crated on xaml. Like that. so I have to create local stack and add controls to the that local stack panel then and after complete I add the local stack panel to xTitlePanel. NOW my code looks like below
filteredList = new List<FormGetSet>();
if (frm_getset.ChildList != null)
{
String[] arr = frm_getset.ChildList.Split(',');
foreach (String x in arr)
{
filteredList.Add(_template.list_fromgetset.Where(p => p.FormID.Contains(x.Trim())).ToList()[0]);
}
}
xTbox_FormNameHeader.Text = frm_getset.NAME;
_Attribute = new List<AttributeGetSet>();
_Attribute = frm_getset.list_attributegetset;
xTitlePanel.Children.Clear();
StackPanel spPanel = new StackPanel();
spPanel.Orientation = System.Windows.Controls.Orientation.Vertical;
spPanel.Background = new SolidColorBrush(Colors.Transparent);
//xTitlePanel.Children.Add(PrepareControls.getControl(1, "LABEL", "16"));
int i = 1;
// List<AttributeGetSet> _Attribute2 = new List<AttributeGetSet>();
foreach (AttributeGetSet a in _Attribute)
{
PrepareControls prepcontrol = new PrepareControls();
StackPanel sp= prepcontrol.getControl(i, a.Label, a, this);
try
{
spPanel.Children.Add(sp);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
//xTitlePanel.Background = new SolidColorBrush(Colors.White);
//_Attribute2.Add(a);
i += 1;
}
xTitlePanel.Children.Add(spPanel);

How to open any specific SettingsFlyout in WinRT app

I am working on a Windows 8 metro app and having multiple SettingsFlyout items which get added by below mentioned code
SettingsCommand cmd1 = new SettingsCommand("sample", "Color Settings", (x) =>
{
// create a new instance of the flyout
SettingsFlyout settings = new SettingsFlyout();
// set the desired width. If you leave this out, you will get Narrow (346px)
// optionally change header and content background colors away from defaults (recommended)
// if using Callisto's AppManifestHelper you can grab the element from some member var you held it in
// settings.HeaderBrush = new SolidColorBrush(App.VisualElements.BackgroundColor);
settings.HeaderBrush = new SolidColorBrush(Colors.Black);
settings.HeaderText = string.Format("Color Settings", App.VisualElements.DisplayName);
settings.Background = new SolidColorBrush(_background);
settings.Margin = new Thickness(0);
// provide some logo (preferrably the smallogo the app uses)
BitmapImage bmp = new BitmapImage(App.VisualElements.SmallLogoUri);
settings.SmallLogoImageSource = bmp;
// set the content for the flyout
settings.Content = new ColorSettings();
settings.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch;
// open it
settings.IsOpen = true;
// this is only for the test app and not needed
// you would not use this code in your real app
// ObjectTracker.Track(settings);
});
Currently using (SettingsPane.Show()) i can be able to show the added flyout items list but I want to programmatically open any setting Flyout item instead of opening a flyout list.
Create a new class
public class SettingsFlyout
{
private const int _width = 346;
private Popup _popup;
/// <summary>
/// Show the Flyout with the UserControl as content
/// </summary>
/// <param name="control"></param>
public void ShowFlyout(UserControl control)
{
_popup = new Popup();
_popup.Closed += OnPopupClosed;
Window.Current.Activated += OnWindowActivated;
_popup.IsLightDismissEnabled = true;
_popup.Width = _width;
_popup.Height = Window.Current.Bounds.Height;
control.Width = _width;
control.Height = Window.Current.Bounds.Height;
_popup.Child = control;
_popup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - _width);
_popup.SetValue(Canvas.TopProperty, 0);
_popup.IsOpen = true;
}
private void OnWindowActivated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
{
_popup.IsOpen = false;
}
}
void OnPopupClosed(object sender, object e)
{
Window.Current.Activated -= OnWindowActivated;
}
}
In a XAML page take a button and then write the button click event.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SettingsFlyout flyout = new SettingsFlyout();
flyout.ShowFlyout(new FlyoutContentUserControl());
}
Please note one thing FlyoutContentUserControl is the user control which you would like to show.
Credits goes to Q42.WinRT
The code you posted registers a SettingsCommands to the system settings pane. When your command is invoked from the system settings pane, you new up a SettingsFlyout instance and set IsOpen=True on it.
You just need to refactor this code to a separate method (e.g. ShowColorSettingsFlyout()), and also call that method from your Button.Click event handler. You can create a new Callisto SettingsFlyout and set IsOpen=True on it anywhere.
In App.xaml.cs add the following to register your SettingsFlyout e.g. CustomSetting ...
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
}
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand(
"Custom Setting", "Custom Setting", (handler) => ShowCustomSettingFlyout()));
}
public void ShowCustomSettingFlyout()
{
CustomSetting CustomSettingFlyout = new CustomSetting();
CustomSettingFlyout.Show();
}
Then anywhere in your code you want to programmatically open the CustomSetting flyout, call ShowCustomSettingFlyout, e.g. in the event handler for a button click...
void Button_Click_1(object sender, RoutedEventArgs e)
{
ShowCustomSettingFlyout()
}
Adapted from: Quickstart: Add app settings (XAML).

Windows 8 Emulator Snap State

How do I enter snap state using the Windows 8 emulator? I received a notice from the Windows 8 store that my software crashes in snap mode only. Does anyone know why switching modes would cause my software to crash? Here is my code behind:
namespace MenuFinderWin8.Pages
{
public sealed partial class RestaurantHomePage : MenuFinderWin8.Common.LayoutAwarePage
{
MenuFinderAppServiceClient serviceClient;
RestaurantRepository repository;
Geolocator _geolocator = null;
ObservableCollection<RestaurantLocation> items;
public RestaurantHomePage()
{
this.InitializeComponent();
if (!Network.IsNetwork())
{
return;
}
repository = new RestaurantRepository();
serviceClient = new MenuFinderAppServiceClient();
_geolocator = new Geolocator();
items = new ObservableCollection<RestaurantLocation>();
BindData();
}
void btnAbout_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
SupportUserControl userControl = new SupportUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 200;
f.Height = 200;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnSearch_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
RestaurantSearchUserControl userControl = new RestaurantSearchUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 600;
f.Height = 400;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnViewFavorites_Click(object sender, RoutedEventArgs e)
{
App.DataMode = Mode.SavedRestaurant;
if (repository.GetGroupedRestaurantsFromDatabase().Count() == 0)
{
MessageDialog messageDialog = new MessageDialog("You have no saved restaurants.", "No Restaurants");
messageDialog.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(RestaurantSearchDetails));
}
}
private async void BindData()
{
try
{
items = await serviceClient.GetSpecialRestaurantsAsync();
List<RestaurantLocation> myFavs = repository.GetRestaurantLocations();
foreach (var a in myFavs)
{
items.Add(a);
}
this.DefaultViewModel["Items"] = items;
}
catch (Exception)
{
MessageDialog messsageDialog = new MessageDialog("The MenuFinder service is unavailable at this time or you have lost your internet connection. If your internet is OK, please check back later.", "Unavailable");
messsageDialog.ShowAsync();
btnAbout.IsEnabled = false;
btnSearch.IsEnabled = false;
btnViewFavorites.IsEnabled = false;
}
myBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
}
private void itemGridView_ItemClick_1(object sender, ItemClickEventArgs e)
{
App.CurrentRestaurantLocation = e.ClickedItem as RestaurantLocation;
if (App.CurrentRestaurantLocation != null)
{
Order order = repository.AddOrder(DateTime.Now, string.Empty, App.CurrentRestaurantLocation.ID);
App.CurrentOrder = order;
App.DataMode = Mode.Menu;
this.Frame.Navigate(typeof(RootViewPage));
}
}
}
}
In response to "How do I enter snap state using the Windows 8 emulator?" - I find the easiest way to snap in the simulator is to use the keyboard shortcut, which is Windows key + . (period).
The error might be in your XAML, more than in the code behind. If you used a template but deleted or modified the name in one of the elements, the KeyFrame refering to that element is failing getting the element, so an exception is thrown.
Search in your XAML for something like
<VisualState x:Name="Snapped">
<Storyboard>...
And delete the ObjectAnimationUsingKeyFrames tags which Storyboard.TargetName property is equal to a non-existant element.
Refering on how to enter Snapped Mode on the emulator, is the same as in PC, just grab the App from the top and slide it to a side while holding the click.

DataBinding Snapped Mode Windows 8

Using a GridView, I bind to several items in an observable collection. When I enter snapped mode, my GridView fails to load any data and none of the items are clickable. See attached screenshot. My app is on the left and it says featured and favorites. Here is my code:
public sealed partial class RestaurantHomePage : MenuFinderWin8.Common.LayoutAwarePage
{
MenuFinderAppServiceClient serviceClient;
RestaurantRepository repository;
Geolocator _geolocator = null;
ObservableCollection<RestaurantLocation> items;
public RestaurantHomePage()
{
this.InitializeComponent();
if (!Network.IsNetwork())
{
return;
}
repository = new RestaurantRepository();
serviceClient = new MenuFinderAppServiceClient();
_geolocator = new Geolocator();
items = new ObservableCollection<RestaurantLocation>();
//BindData();
}
void btnAbout_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
SupportUserControl userControl = new SupportUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 200;
f.Height = 200;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnSearch_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
RestaurantSearchUserControl userControl = new RestaurantSearchUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 600;
f.Height = 400;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnViewFavorites_Click(object sender, RoutedEventArgs e)
{
App.DataMode = Mode.SavedRestaurant;
if (repository.GetGroupedRestaurantsFromDatabase().Count() == 0)
{
MessageDialog messageDialog = new MessageDialog("You have no saved restaurants.", "No Restaurants");
messageDialog.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(RestaurantSearchDetails));
}
}
private async void BindData()
{
try
{
items = await serviceClient.GetSpecialRestaurantsAsync();
List<RestaurantLocation> myFavs = repository.GetRestaurantLocations();
foreach (var a in myFavs)
{
items.Add(a);
}
this.DefaultViewModel["Items"] = items;
}
catch (Exception)
{
MessageDialog messsageDialog = new MessageDialog("The MenuFinder service is unavailable at this time or you have lost your internet connection. If your internet is OK, please check back later.", "Unavailable");
messsageDialog.ShowAsync();
btnAbout.IsEnabled = false;
btnSearch.IsEnabled = false;
btnViewFavorites.IsEnabled = false;
}
myBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
BindData();
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
}
private void itemGridView_ItemClick_1(object sender, ItemClickEventArgs e)
{
App.CurrentRestaurantLocation = e.ClickedItem as RestaurantLocation;
if (App.CurrentRestaurantLocation != null)
{
Order order = repository.AddOrder(DateTime.Now, string.Empty, App.CurrentRestaurantLocation.ID);
App.CurrentOrder = order;
App.DataMode = Mode.Menu;
this.Frame.Navigate(typeof(RootViewPage));
}
}
}
When you switch to snapped view, your gridView hides, and a ListView shows up. You can see this by checking the Visual State Manager that handles going from one to another in your XAML.
So, Solution is: adapting the ItemTemplate from your ListView as you did with your GridView by Binding to the proper attributes; you may also want to change the Foreground color of your Font. Also, you want to include the IsItemClickEnabled and ItemClick (or SelectionMode and SelectionChanged) on your ListView.

how to make textbox content shareable in windows 8 xaml app when user clicks share from charm settings?

I have one text textbox in my Windows8 Store app (xaml) application and I want to make it shareable when user selects Share option from Charm settings ? Is that possible to in windows 8 store xaml app ?
Yes, you need to respond to the "DataRequested" event and add the content of the textbox to the data package. Here is a code sample:
JavaScript:
// Call this during initialization
function registerForShare() {
var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
dataTransferManager.addEventListener("datarequested", shareTextHandler);
}
function shareTextHandler(e) {
var request = e.request;
request.data.properties.title = "Your title";
request.data.properties.description = "Description of what you're sharing";
request.data.setText(yourTextBox.Text);
}
C#:
// Call this during initialization
private void ShareSourceLoad()
{
var dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += DataRequested;
}
private void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Your title";
request.Data.Properties.Description = "Description of what you're sharing";
request.Data.SetText(yourTextBox.Text);
}