Use a Single Object Reference Globally in a UWP Application

Sometimes you might want a single object reference that can be accessed from any page within your application.  Creating an instance of it on the App using App.Current may be appropriate.

In this example we’re using a string, but you could easily use a custom object of your own creation.

In the App.xaml.cs file:

sealed partial class App : Application
{
  public string SomeValue;

  /// <summary>
  /// Initializes the singleton application object. This is the first line of authored code
  /// executed, and as such is the logical equivalent of main() or WinMain().
  /// </summary>
  public App()
  {
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    // Do any initiation work here - just don't break the app 
    // or do anything that will slow it down too much.
    SomeValue = "New Value";
  }
}

To use in your code, e.g. on some page somewhere:

public sealed partial class SomePage : Page
{
  App _AppReference = App.Current as App;

  void SomeMethod()
  {
    _AppReference.SomeValue = "New Value";
  }
}

 

 

Advertisements

Using the Clipboard in UWP

How to Copy to Clipboard (Text String)

using Windows.ApplicationModel.DataTransfer;

...

dataPackage = new DataPackage();
dataPackage.RequestedOperation = DataPackageOperation.Copy;
dataPackage.SetText(text);
Clipboard.SetContent(dataPackage);

 

How to Paste from Clipboard (Image/Bitmap Data)

using Windows.Storage.AccessCache;
using Windows.Storage.Streams;

...

DataPackageView dataPackageView = Clipboard.GetContent();

if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
  IRandomAccessStreamReference imageReceived = null;
  imageReceived = await dataPackageView.GetBitmapAsync();
  if (imageReceived != null)
  {
    using (var imageStream = await imageReceived.OpenReadAsync())
    {
      var bitmapImage = new BitmapImage();
      bitmapImage.SetSource(imageStream);
      imgImage.Source = bitmapImage;

      dec = await BitmapDecoder.CreateAsync(imageStream);

      // https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder
      // https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder.getpixeldataasync#Windows_Graphics_Imaging_BitmapDecoder_GetPixelDataAsync
      var data = await dec.GetPixelDataAsync();

      imgBytes = data.DetachPixelData();
      imgWidth = dec.OrientedPixelWidth;
      imgHeight = dec.OrientedPixelHeight;

      // FYI, Overall image L-R, Top-Bottom.
      // Groups in reverse order: BGRA BGRA BGRA

      ByteArrayToPixelMap(imgBytes);
    }
  }
}

Dynamically Populate a UWP Grid using C#

This technique works for columns and rows, you just have to use the correct definition object, ColumnDefinition or RowDefinition.

Note the references to your specific grid instance (e.g. myGrid) and Grid methods (e.g. Grid.SetRow()).

myGrid.Children.Clear();
myGrid.ColumnDefinitions.Clear();

ColumnDefinition colDef;

for(int i = 0; i < myArray.Length; i++)
{
  colDef = new ColumnDefinition();
  myGrid.ColumnDefinitions.Add(colDef);
  colDef.MinWidth = 50;

  // Create a new instance of a TextBlock
  // or any other control; making a factory 
  // method(s) is usually wise.
  TextBlock txt = MyTextBlockFactoryMethod();
  myGrid.Children.Add(txt);
  Grid.SetRow(txt, 0);
  Grid.SetColumn(txt, i);
  txt.Text = myArray[i].ToString();
}

Application Version Info Panel

Here’s how to build a simple panel that shows the user the version info of your UWP application.

First the XAML / UI:

<Border x:Name="pnlInstallLocation" Padding="10" CornerRadius="5" Background="#FFB9D2F6" Margin="0,5,15,0" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
  <RelativePanel>
    <TextBlock x:Name="lbllocation">Install Details</TextBlock>
    <TextBlock x:Name="txtBuildDetails" Text="[build details]" RelativePanel.Below="lbllocation" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" MinHeight="12" Margin="10,0,0,0" />
    <TextBox x:Name="txtVersion" Text="[version]" RelativePanel.Below="txtBuildDetails" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" IsReadOnly="True" BorderThickness="0" Background="Transparent" MinHeight="12" Margin="10,0,0,0" />
    <TextBox x:Name="txtLocation_App" Text="[location]" RelativePanel.Below="txtVersion" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" IsReadOnly="True" BorderThickness="0" Background="Transparent" Height="20" MinHeight="12" Margin="10,0,0,0" />
    <TextBox x:Name="txtLocation_DB" Text="[location]" RelativePanel.Below="txtLocation_App" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" IsReadOnly="True" BorderThickness="0" Background="Transparent" Height="20" MinHeight="12" Margin="10,0,0,0" />
  </RelativePanel>
</Border>

The code behind:

using Windows.ApplicationModel;

private void Page_Loaded(object sender, RoutedEventArgs e)
{
  Package package = Package.Current;
  PackageId packageId = package.Id;
  PackageVersion version = packageId.Version;

  txtBuildDetails.Text = string.Format("{3} ({4}){0}Package {2}{0}Installed {1}", 
    Environment.NewLine,
    package.InstalledDate, package.Id.Name,
    package.DisplayName, package.Id.Architecture);

  txtVersion.Text = string.Format("Version {0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);

  txtLocation_App.Text = string.Format("Application folder {0}", package.InstalledLocation.Path);
  txtLocation_DB.Text = string.Format("Database folder {0}", ApplicationData.Current.LocalFolder.Path);


  #if DEBUG
  txtVersion.Foreground = new SolidColorBrush(Windows.UI.Colors.DarkRed);
  #endif
}

 

This code has been lifted from a working app, I haven’t done a detailed checking of the code for this post, but everything needed should be present – uses Windows 10 Anniversary Edition (10.0; Build 14393).

Using Symbols in UWP UI Controls

To use a symbol character from a font like Segoe MDL2 Assets or Segoe UI Symbol as the visible content / text of a UWP control in XAML, use the following schema: &#x1234; where 1234 is the correct symbol code.

E.g.:

<Button x:Name="btnDoSomething" FontFamily="Segoe MDL2 Assets" Content="&#x1234;"></Button>

To set in C# use:

lblMySymbol.Text = "\u1234";

Also see:

  1. https://docs.microsoft.com/en-us/windows/uwp/design/style/segoe-ui-symbol-font
  2. https://www.google.co.nz/search?q=segoe+mdl2+assets+cheatsheet
  3. http://www.kreativekorp.com/charset/font.php?font=Segoe+UI+Symbol

 

About These Code Posts

I no longer code to earn a living, I code for pleasure.  The code snippets posted here are mainly for my own reference – and to benefit anyone who can use them.