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, PageStyle

Windows UWP (Universal Windows Platform) is a platform for creating applications that can run on a variety of devices. One of the key elements of this platform is pages and styles, which allow defining UI components and managing resources. In this tutorial, we will delve into the concept of PageStyle in UWP and explain it in detail with example code.

1. UWP Application Structure

UWP applications can consist of multiple pages, each providing the UI that users interact with. Typically, a UWP application has the following structure:

  • App.xaml: Defines the resources to be used throughout the application and the application startup.
  • MainPage.xaml: The main page that users encounter first.
  • Multiple additional pages: Various pages can be added depending on the functionality of the app.

2. Concept of Page Styles

Page styles are crucial elements for designing the UI of UWP applications. They are defined using XAML (Extensible Application Markup Language). Through page styles, you can control elements such as:

  • Colors and backgrounds
  • Fonts and text sizes
  • Margins and padding
  • Behavior and interaction of UI components

3. Using Styles in XAML

Defining and applying styles in XAML is very straightforward. Styles are generally defined in a ResourceDictionary and can be applied to each UI element. The example below shows how to define and apply button styles in XAML.

Example: Defining Button Style

    
    <Page.Resources>
        <Style x:Key="MyButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Blue"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="Padding" Value="10"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="FontSize" Value="16"/>
            <Setter Property="CornerRadius" Value="5"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkBlue"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Page.Resources>

    <Button Style="{StaticResource MyButtonStyle}" Content="Click Me" />
    
    

4. Managing Resources and Styles

Managing resources in a UWP application is essential for maintaining design consistency and enhancing code reusability. By utilizing a ResourceDictionary, you can centrally manage colors, fonts, styles, and more. The following is an example of defining colors in a resource dictionary.

Example: Defining Colors

    
    <Page.Resources>
        <SolidColorBrush x:Key="PrimaryColor" Color="#FF5733"/>
        <SolidColorBrush x:Key="SecondaryColor" Color="#33FF57"/>
    </Page.Resources>

    <TextBlock Text="Hello, UWP!" Foreground="{StaticResource PrimaryColor}" FontSize="24" />
    
    

5. Sharing Styles Between Pages

In UWP applications, styles can be shared between multiple pages. This reduces code duplication and maintains style consistency. By defining styles in App.xaml, they can be used across all pages in the application.

Example: Defining Styles in App.xaml

    
    <Application.Resources>
        <Style x:Key="GlobalButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Foreground" Value="White"/>
        </Style>
    </Application.Resources>

    <Button Style="{StaticResource GlobalButtonStyle}" Content="Global Button" />
    
    

6. Animations and Styles

In UWP, you can add animations using XAML to make the UI more appealing. Using animations along with styles can enhance the user experience. Below is an example of applying animations when a button is clicked.

Example: Button Click Animation

    
    <Button Content="Animate Me">
        <Button.RenderTransform>
            <CompositeTransform x:Name="buttonTransform" />
        </Button.RenderTransform>
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="buttonTransform" Storyboard.TargetProperty="ScaleX" To="1.2" Duration="0:0:0.2" AutoReverse="True" />
                        <DoubleAnimation Storyboard.TargetName="buttonTransform" Storyboard.TargetProperty="ScaleY" To="1.2" Duration="0:0:0.2" AutoReverse="True" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Button.Triggers>
    </Button>
    
    

7. Conclusion

In UWP development, page styles are crucial elements that determine the overall appearance and user experience of the application. Styles can be easily defined and applied with XAML, and by managing resources efficiently, code reusability can be enhanced. When combined with animations, users can experience a richer and more engaging interface.

Through further research and learning, you can advance the design and styling of UWP applications. I hope you can refer to this content in future projects to provide a better user experience.