UWP Development, Resources Provided by Prism

UWP (Universal Windows Platform) development is a platform for developing applications that run on Windows 10 and later Windows operating systems. These applications can run on various devices (PCs, tablets, Xbox, etc.) and provide a high level of user experience in terms of user interface (UI), performance, accessibility, security, and more. In UWP development, Prism is a useful framework that supports the MVVM (Model-View-ViewModel) architectural pattern, and the various resources provided within this framework contribute to enhancing the quality and productivity of applications.

Overview of the Prism Framework

Prism is a framework that can be used across several platforms like WPF (Windows Presentation Foundation), Xamarin.Forms, and UWP. It primarily offers the following features:

  • Modularity: It separates the application into smaller modules, making it easier to manage.
  • Support for MVVM Pattern: It enhances testability and maintainability by separating the view and business logic.
  • Command and Event Aggregator: Simplifies communication between components.
  • Navigation: Supports efficient and clear transitions between pages.

Resources of Prism

Prism maximizes development efficiency by defining and reusing shareable resources. These resources are primarily provided in the following forms:

1. Styles

Various styles can be defined to maintain UI consistency in UWP applications. Prism provides several common styles by default. These styles are managed through a `ResourceDictionary` and can be easily used in XAML.



    

2. Control Templates

Control Templates define the appearance of UI elements. Prism provides reusable Control Templates to maintain consistent visual representation of various UI elements.



    
        
    

3. Converters

Converters are resources used to transform data types during data binding. Prism provides several built-in converters to support binding according to the type of data.


public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool boolean)
        {
            return boolean ? Visibility.Visible : Visibility.Collapsed;
        }
        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value is Visibility visibility && visibility == Visibility.Visible;
    }
}

4. Behaviors

Behaviors are functionalities that work alongside UI elements to add behavior. Prism provides various Behaviors to easily add new functionalities to UI components. This enhances code decoupling and reusability.



Example of Using Prism Resources

Below is an example of developing a UWP application using Prism’s resources. This example implements a simple application that displays a message when the user clicks a button.

1. XAML Setup

First, we define the Styles, Control Templates, and Behaviors that will be used in the MainPage.xaml file.



    
    
        
            
        
    

    
        
    

2. ViewModel Setup

Next, we create the ViewModel to define the action that occurs on button click.


using Prism.Commands;
using Prism.Mvvm;
using System;

namespace MyApp.ViewModels
{
    public class MainPageViewModel : BindableBase
    {
        private string _message;
        public string Message
        {
            get { return _message; }
            set { SetProperty(ref _message, value); }
        }

        public DelegateCommand MyCommand { get; private set; }

        public MainPageViewModel()
        {
            MyCommand = new DelegateCommand(OnMyCommandExecuted);
        }

        private void OnMyCommandExecuted()
        {
            Message = "Button was clicked!";
        }
    }
}

3. App Entry Point Setup

Finally, we set up the entry point of the application and bind the View and ViewModel.


using Prism.Ioc;
using Prism.Unity;
using Windows.UI.Xaml;
using MyApp.Views;

namespace MyApp
{
    sealed partial class App : PrismApplication
    {
        public App() : base() { }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation();
        }

        protected override void OnInitialized()
        {
            this.InitializeComponent();
            NavigationService.NavigateAsync("MainPage");
        }
    }
}

Conclusion

By appropriately utilizing the resources provided by Prism when developing UWP applications, you can write more efficient and maintainable code. Styles, Control Templates, Converters, and Behaviors are all elements that enhance the UI and user experience of the application. Through these resources, you can increase code reusability and deepen your understanding of the MVC pattern.

I hope this blog post helps you understand how to utilize Prism’s resources and apply them in actual applications. UWP development will offer more opportunities in the future, and Prism is one of the best tools to accompany you on this journey.

References

UWP Development, Creating a New Project Based on the Prism Framework

Write date: October 10, 2023

1. What is UWP?

UWP (Universal Windows Platform) is a platform from Microsoft that allows you to develop applications that run on a variety of devices (PCs, tablets, smartphones, etc.). UWP maximizes developer productivity by enabling the creation of apps that can run on multiple devices with a single codebase.

Key features of UWP include the ability to run apps on various platforms such as mobile, PC, and Xbox,
XAML-based UI composition, and the provision of various APIs for modern app development.
Thanks to these advantages, UWP is becoming increasingly popular among developers.

2. What is the Prism Framework?

The Prism Framework is a library designed to enhance the quality and maintainability of XAML-based applications such as WPF, Xamarin.Forms, and UWP.
It adopts the MVVM (Model-View-ViewModel) pattern to help developers easily organize and manage their apps.

Prism provides the following key features:

  • Modularity: Applications can be divided into multiple modules, distributing work and increasing code reuse.
  • Dependency Injection: It provides an easy-to-manage structure for necessary components, making it convenient for testing.
  • Event Aggregation: It effectively manages and binds a variety of events and commands.

3. Installing the Prism Framework

To use the Prism Framework, you need to install the NuGet package.
After creating a new UWP project in Visual Studio, install the required Prism package through the NuGet Package Manager as follows:

Install-Package Prism.Windows

Once the installation is complete, the basic structure of the project is ready.

4. Creating a New UWP Project

Launch Visual Studio and select the ‘Create a new project’ option. In the ‘Platform’
category, choose ‘Windows’, and then select ‘UWP App’.

After setting the project name and save location, click the ‘Create’ button to generate the new project.

5. Setting Up the Prism-Based Structure

To introduce the Prism Framework into the newly created UWP project, you need to set up the basic structure.
In this step, modify the App.xaml.cs file to set it up as a Prism Application.

using Prism;
using Prism.Ioc;
public sealed partial class App : PrismApplication
{
    public App() : base() { }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        // Register services here.
    }

    protected override void OnInitialized()
    {
        InitializeComponent();
        NavigationService.NavigateAsync("MainPage");
    }
}

6. Creating and Configuring Modules

Another advantage of Prism is support for modularity. You can manage each feature as a separate module.
Create a new module and write the Registration file.

public class MyModule : IModule
{
    public void OnInitialized()
    {
        // Called when the module is initialized.
    }

    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation();
    }
}

7. Implementing the MVVM Pattern

Implement the MVVM pattern using UWP and Prism. Create a ViewModel and bind it to the View to easily manage data and testing.

public class MainViewModel : BindableBase
{
    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public MainViewModel()
    {
        Title = "Hello, Prism!";
    }
}

8. Implementing Pages and Data Binding

Bind the ViewModel in MainPage.xaml to create interaction with UI elements.
Below is a simple example of XAML code.

<Page x:Class="YourAppNamespace.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>
        <TextBlock Text="{Binding Title}" 
                   FontSize="24" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center"/>
    </Grid>
</Page>

9. Testing and Debugging

After building the application, run debugging and testing before deploying to the UWP store.
Utilize Visual Studio’s debugging tools to quickly identify problems in the code.

10. Conclusion and Additional Resources

Through the above steps, I hope you have gained an understanding of the basic flow of UWP app development using the Prism Framework.
I encourage you to refer to websites and books for deeper learning.
Check out the official Prism documentation or
Getting Started with UWP.

© 2023 Developer Blog. All rights reserved.

UWP Development, Pen and Shape

UWP (Universal Windows Platform) is a platform provided by Microsoft that allows applications to be developed for various devices running Windows 10. This article will explain in detail how to draw graphics using Pen and Shape in UWP.

Overview of Graphics Processing in UWP

In UWP, XAML and C# are used for graphics processing, enabling developers to easily and quickly create UIs and implement interactions with users. Pen and Shape play important roles in this graphic implementation.

Introduction to Pen

The Pen object is a tool used to draw lines, curves, or other paths. The Pen can specify the thickness, color, style, and more of the line.

using Windows.UI.Xaml.Media;
// Create a Pen object
var myPen = new Pen
{
    Brush = new SolidColorBrush(Windows.UI.Colors.Blue),
    Thickness = 2
};

Introduction to Shape

Shape is a class for drawing basic shapes. There are several Shape classes available in UWP, including Rectangle, Ellipse, Line, Polygon, and Path. Each class is used to represent various shapes.

Basic Pen Usage Example

The code below is a simple example of drawing a line on a Canvas using Pen in a UWP application.

<Canvas x:Name="myCanvas">
    <Path Stroke="{StaticResource MyPen}" Data="M 20,20 L 200,200" />
</Canvas>

private void DrawLine()
{
    var myPen = new Pen
    {
        Brush = new SolidColorBrush(Windows.UI.Colors.Red),
        Thickness = 3
    };
    
    var line = new Line
    {
        X1 = 20,
        Y1 = 20,
        X2 = 200,
        Y2 = 200,
        Stroke = myPen.Brush,
        StrokeThickness = myPen.Thickness
    };

    myCanvas.Children.Add(line);
}

Examples of Various Shapes

UWP allows you to use various Shapes. Below is an example of drawing a Rectangle and an Ellipse.

<Canvas x:Name="myCanvas">
    <Rectangle Width="100" Height="50" Fill="Green" />
    <Ellipse Width="100" Height="50" Fill="Blue" />
</Canvas>

private void DrawShapes()
{
    var rectangle = new Rectangle
    {
        Width = 100,
        Height = 50,
        Fill = new SolidColorBrush(Windows.UI.Colors.Green)
    };

    var ellipse = new Ellipse
    {
        Width = 100,
        Height = 50,
        Fill = new SolidColorBrush(Windows.UI.Colors.Blue)
    };

    myCanvas.Children.Add(rectangle);
    myCanvas.Children.Add(ellipse);
}

Adding Interactions

After drawing graphics with Pen and Shape, you can add interactions with users. For example, here is how to change the color of a shape when the mouse is clicked.

private void myCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)
{
    var point = e.GetCurrentPoint(myCanvas).Position;
    var ellipse = new Ellipse
    {
        Width = 50,
        Height = 50,
        Fill = new SolidColorBrush(Windows.UI.Colors.Red),
        Margin = new Thickness(point.X, point.Y, 0, 0)
    };
    myCanvas.Children.Add(ellipse);
}

Utilizing the Combination of Pen and Shape in UWP

Pen and Shape can be used together to create complex graphics easily. For example, it is possible to combine multiple Shapes to create a complex figure. Additionally, the path of the Shape can be drawn using the Pen.

private void DrawComplexShape()
{
    var myPath = new Path
    {
        Stroke = new SolidColorBrush(Windows.UI.Colors.Black),
        StrokeThickness = 1,
        Data = Geometry.Parse("M 10,100 C 20,10, 40,10, 50,100")
    };

    myCanvas.Children.Add(myPath);
}

Performance Optimization

Optimizing performance while using Pen and Shape in UWP is very important. Especially when drawing a large number of shapes, performance degradation might occur, so batching and offscreen rendering should be considered.

private void OptimizeRendering()
{
    var visualLayer = new DrawingVisual();
    using (var dc = visualLayer.RenderOpen())
    {
        for (int i = 0; i < 1000; i++)
        {
            dc.DrawEllipse(new SolidColorBrush(Colors.Blue), null, new Point(i * 10, i * 10), 5, 5);
        }
    }
}

Conclusion

This article discussed how to utilize Pen and Shape in UWP. With Pen and Shape, developers can implement a variety of graphics, providing a richer and more intuitive UI. The code examples shown demonstrate practical implementation methods that you can apply in your applications.

UWP Development, Path

UWP (Universal Windows Platform) is a platform for developing applications on various Windows devices, providing modern UI and powerful features. In this blog post, we will explore the role and usage of Path in UWP and how to utilize it through various examples.

What is Path?

Path is a powerful tool used to draw vector graphics in UWP. The Path object, which can be defined in XAML (XML Application Markup Language), can define complex shapes and graphics. Through Path, users can easily create various shapes and apply animations, styling, and transformations.

Main Components of Path

Path consists of several components, with the most important ones being:

  • Data: Defines the shape of the figures that make up the Path. This allows you to define lines, curves, polylines, and more.
  • Stroke: Defines the color and thickness of the outer lines of the Path. This sets the boundaries of the shapes.
  • Fill: Defines the internal color of the Path. This sets the color used to fill the shapes.
  • Transforms: Defines the transformations applied to the Path. This allows for movement, rotation, scaling, and more.

How to Use Path

To use Path, you can define shapes using the Path tag in XAML. Let’s look at a basic example of using Path.

Basic Path Example

<Path Fill="Blue" Stroke="Black" StrokeThickness="2">
    <Path.Data>
        <GeometryGroup>
            <RectangleGeometry Rect="10,10,100,50" />
            <EllipseGeometry Center="60,60" RadiusX="30" RadiusY="30" />
        </GeometryGroup>
    </Path.Data>
</Path>

The example above draws a rectangle and a circle filled with blue. The Fill and Stroke properties set the colors, and the StrokeThickness property adjusts the line thickness.

Path Animation

Path can provide a more attractive UI by applying animation effects. In UWP, you can add animations to Path using Storyboard.

Path Animation Example

<Page.Resources>
    <Storyboard x:Name="PathAnimation">
        <DoubleAnimation 
            Storyboard.TargetName="MyPath" 
            Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" 
            From="0" To="360" Duration="0:0:2" 
            RepeatBehavior="Forever" />
    </Storyboard>
</Page.Resources>

<Path x:Name="MyPath" Fill="Red" Stroke="Black" StrokeThickness="2" RenderTransform="RotateTransform">
    <Path.Data>
        <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
    </Path.Data>
</Path>

<Button Content="Start" Click="StartAnimation" />

In the example above, clicking the ‘Start’ button initiates an animation where a red circle rotates 360 degrees over 2 seconds. The RepeatBehavior property can be used to set whether the animation repeats.

Path Transform

You can apply various transformation effects using the Transform property of Path. It allows easy modification of the Path’s position and shape through movement (Move), rotation (Rotate), and scaling (Scale).

Path Transformation Example

<Path Fill="Green" Stroke="Black" StrokeThickness="2">
    <Path.RenderTransform>
        <TransformGroup>
            <RotateTransform Angle="45" />
            <TranslateTransform X="30" Y="30" />
        </TransformGroup>
    </Path.RenderTransform>
    <Path.Data>
        <RectangleGeometry Rect="0,0,100,50" />
    </Path.Data>
</Path>

The example above rotates a green rectangle by 45 degrees and moves its position by 30 units on the X-axis and 30 units on the Y-axis. You can combine multiple transforms to apply to the Path.

Path and Events

Path can handle events for user interaction. You can add mouse events to the Path object so that users can interact with the shapes directly.

Mouse Click Event Example

<Path Fill="Purple" Stroke="Black" StrokeThickness="2" MouseLeftButtonDown="Path_Click">
    <Path.Data>
        <EllipseGeometry Center="100,100" RadiusX="50" RadiusY="50" />
    </Path.Data>
</Path>

The example above defines a Path_Click event that executes when the Path is clicked. This event can allow additional actions to be performed based on the Path clicked by the user in C# code.

C# Code Example

private void Path_Click(object sender, MouseButtonEventArgs e) {
    MessageBox.Show("Path was clicked!");
}

Path and Data Binding

In UWP, Path can dynamically change the properties of shapes through data binding when using the MVVM pattern. This allows the Path’s UI to automatically update according to changes in data.

Data Binding Example

<Path Fill="{Binding Color}" Stroke="Black" StrokeThickness="2">
    <Path.Data>
        <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
    </Path.Data>
</Path>

The example above defines a Path bound to the Color property. If the Color property changes, the Path’s Fill property will also update automatically.

Conclusion

Using Path in UWP allows for easy implementation of complex graphics and animations. Utilize various properties and methods to create a creative and interactive user interface. This blog post covered the basic concepts of Path along with various use cases. I hope you can add more attractive graphics to your UWP applications through Path.

UWP Development, Navigation

Navigation is a key element of user experience in Universal Windows Platform (UWP) development. Users should be able to easily access and navigate through various screens and data. This article will discuss how to implement navigation in UWP applications and various techniques related to it.

1. Understanding UWP Navigation

Navigation refers to the transition between screens within an application, allowing users to explore different parts of the application. In UWP, navigation between pages is primarily managed using the Frame class. Each page is defined by inheriting the Page class.

1.1 Frame and Page

The Frame is a control that provides page transitions. Users can switch to a new page through the Frame and can navigate back to the previous page using the GoBack and GoForward methods.

1.2 Creating a Page

To create a new page, you can use the Page template in Visual Studio to generate a file. Below is an example of a basic page class:

using Windows.UI.Xaml.Controls;

namespace YourAppNamespace
{
    public sealed partial class SamplePage : Page
    {
        public SamplePage()
        {
            this.InitializeComponent();
        }
    }
}

2. Methods of Navigation

UWP provides various methods for navigation. The most common methods include:

  • Direct navigation through frames
  • Page transition on button click
  • Navigation through model binding

2.1 Direct Navigation through Frames

You can navigate directly to another page using the frame. The Navigate method of the frame object is used to switch pages. The example below shows how to move from MainPage to SamplePage:

private void NavigateToSamplePage()
{
    this.Frame.Navigate(typeof(SamplePage));
}

2.2 Page Transition on Button Click

You can implement navigation to a specific page when a user clicks a button. Below is an example of transitioning pages through a button click event:

<Button Content="Go to Sample Page" Click="NavigateButton_Click" />

private void NavigateButton_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(SamplePage));
}

2.3 Navigation through Model Binding

When using the MVVM pattern, navigation can be implemented through commands in the view model. Below is an example of navigation through model binding using the ICommand interface:

using System.Windows.Input;

public class MainViewModel
{
    public ICommand NavigateCommand { get; private set; }

    public MainViewModel()
    {
        NavigateCommand = new RelayCommand(Navigate);
    }

    private void Navigate()
    {
        // Page navigation code
    }
}

3. Backward and Forward Navigation

UWP also provides functionality to return to the previous page. Allowing users to easily return to the previous page is an important element that enhances user experience. The Frame class allows checking the status of the current navigation history through the CanGoBack and CanGoForward properties.

if (this.Frame.CanGoBack)
{
    this.Frame.GoBack();
}

4. Example Application of UWP Navigation

Now let’s create a simple UWP navigation example application. This application consists of two pages and switches pages through button clicks.

4.1 MainPage.xaml

<Page
    x:Class="YourAppNamespace.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:YourAppNamespace"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Content="Go to Sample Page" Click="NavigateButton_Click" />
    </StackPanel>
</Page>

4.2 SamplePage.xaml

<Page
    x:Class="YourAppNamespace.SamplePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:YourAppNamespace"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock Text="Sample Page" FontSize="24" />
        <Button Content="Go Back" Click="GoBackButton_Click" />
    </StackPanel>
</Page>

4.3 MainPage.xaml.cs

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace YourAppNamespace
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void NavigateButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(SamplePage));
        }
    }
}

4.4 SamplePage.xaml.cs

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace YourAppNamespace
{
    public sealed partial class SamplePage : Page
    {
        public SamplePage()
        {
            this.InitializeComponent();
        }

        private void GoBackButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.Frame.CanGoBack)
            {
                this.Frame.GoBack();
            }
        }
    }
}

5. Conclusion

Navigation in UWP applications is a factor that greatly enhances the user experience. By using Frame and Page, it is easy to switch between multiple pages and provide users with intuitive and flexible navigation in various ways. The topics discussed in this article can be useful for implementing more complex applications.

6. Additional Resources

If you’re looking for more in-depth information about UWP navigation, please refer to the following links: