UWP Development, Order of Resource Application and Scope of Application

In Universal Windows Platform (UWP) development, “Resource” refers to reusable components for various elements.
Resources are primarily defined in XAML and exist in various forms such as styles, templates, images, and strings.
In this article, we will explain the order of application and scope of Resources in UWP development in detail and provide
example code to aid understanding.

1. Types of Resources

In UWP, Resources are divided into several types, each with different usage methods and application scopes.
Here we will introduce the most commonly used types of Resources.

  • XAML Resource Dictionary: A structure that groups multiple Resources for reuse.
  • StaticResource: A method that pre-loads resources when the application starts.
  • DynamicResource: Allows defining resources that can be changed later.
  • Styles and ControlTemplates: Define the style and template of UI elements to implement a consistent UI.

2. Order of Resource Application

When applying Resources in UWP, there is a specific order that determines how and to which elements Resources apply.
Resources are prioritized and applied in the following order.

  1. Local Resource: Resources defined directly within the XAML file take precedence.
  2. Page Resource: Resources defined on the XAML page are applied second.
  3. Application Resource: Resources defined within the App.xaml file are applied next.
  4. System Resource: The built-in default Resources of Windows are applied last.

3. Scope of Resource Application

Resources are used within a specific scope, which varies depending on where the Resource is defined.
The application scope of each Resource is as follows.

  • Local Resource: Local Resources are only valid within the corresponding XAML element.
  • Page Resource: Page Resources apply to all child elements within the corresponding XAML page.
  • Application Resource: Application Resources are accessible across all pages of the app and can be reused throughout the app.

4. Example Code

To understand the types, application order, and scope of Resources, let’s look at some example codes.

4.1 Local Resource Example


    <Grid>
        <Grid.Resources>
            <SolidColorBrush x:Key="LocalBrush" Color="Red"/>
        </Grid.Resources>
        <Rectangle Width="100" Height="100" Fill="{StaticResource LocalBrush}"/>
    </Grid>
    

4.2 Page Resource Example


    <Page.Resources>
        <Style x:Key="MyButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Blue"/>
            <Setter Property="Foreground" Value="White"/>
        </Style>
    </Page.Resources>

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

4.3 Application Resource Example


    <Application.Resources>
        <ResourceDictionary>
            <SolidColorBrush x:Key="AppBrush" Color="Green"/>
        </ResourceDictionary>
    </Application.Resources>

    <Rectangle Fill="{StaticResource AppBrush}" Width="100" Height="100"/>
    

5. Dynamic Changes to Resources

UWP also supports the ability to dynamically change Resources.
Using DynamicResource allows for runtime changes to Resources.


    <Grid>
        <Grid.Resources>
            <SolidColorBrush x:Key="RectangleBrush" Color="Orange"/>
        </Grid.Resources>
        <Rectangle Width="100" Height="100" Fill="{DynamicResource RectangleBrush}"/>
    </Grid>

    // Dynamically change the Brush color
    var brush = (SolidColorBrush)Resources["RectangleBrush"];
    brush.Color = Colors.Purple;
    

6. Considerations When Using Resources

When using Resources, there are several considerations to keep in mind.

  • Memory Usage: Excessive resource usage may lead to memory issues, especially with large images or complex templates.
  • Permissions: Consider permission-related issues when accessing Resources.
  • Performance: Animated Resources or large images may affect application performance.

7. Conclusion

In UWP development, Resources are a powerful tool for efficiently managing and reusing UI components.
Understanding and applying the correct usage of Resources will greatly contribute to the quality of UWP application development.
We hope that through the types, application order, scope, and usage examples of Resources introduced in this article,
you can develop robust UWP applications.

Author: [Your Name]

UWP Development, Routed Event

In Universal Windows Platform (UWP) development, events play an important role. Events are essential elements that connect the user interface (UI) and user interactions. To handle events, event handlers are needed, and Routed Events describe the mechanism by which events propagate within a UWP application. In this article, we will explore the concept of Routed Events, usage examples, and various programming techniques in detail.

What is a Routed Event?

A Routed Event is a pattern for events that occur in UWP, where events can propagate from the element that raised them to its parent element or from a parent element to its child elements. This structure allows events to be handled only at desired locations, simplifying interactions between various elements in the UI tree.

Routed Events have three main propagation directions:

  • Bubbling: Events propagate from child elements to parent elements. This usually occurs when UI elements are manipulated.
  • Tunneling: Events travel down from parent elements to child elements. This method is useful when you want to use higher-priority event handlers.
  • Direct: Events are handled directly by specific elements. This is used when performing basic event handling.

Creating a Routed Event

Routed Events can be created as custom events. Here’s how to create a Routed Event in UWP:

csharp
// Registering an event with RoutedEventManager
public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent(
    "MyCustom",
    RoutingStrategy.Bubbling,
    typeof(RoutedEventHandler),
    typeof(MyControl));

public event RoutedEventHandler MyCustom
{
    add { AddHandler(MyCustomEvent, value); }
    remove { RemoveHandler(MyCustomEvent, value); }
}

// Method to raise the event
protected virtual void RaiseMyCustomEvent()
{
    RoutedEventArgs args = new RoutedEventArgs(MyCustomEvent);
    RaiseEvent(args);
}

In the code above, we created a custom control called MyControl and registered a Routed Event named MyCustomEvent. Event handlers can be added and removed via the MyCustom property. Finally, the RaiseMyCustomEvent method is responsible for raising the event.

Using Routed Events

Now that we have created a custom Routed Event, it’s time to actually use it. Let’s see how we can leverage Routed Events through the example below:

csharp
// Custom control class
public sealed class MyControl : Control
{
    public MyControl()
    {
        this.DefaultStyleKey = typeof(MyControl);
        this.PointerPressed += OnPointerPressed; // Handling pointer click events
    }

    private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
    {
        RaiseMyCustomEvent(); // Raising MyCustom event
    }
}

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

    <StackPanel>
        <local:MyControl MyCustom="MyControl_MyCustom"/>
    </StackPanel>
</Page>

// Event handler (XAML.cs)
private void MyControl_MyCustom(object sender, RoutedEventArgs e)
{
    // Handling the custom event
    Debug.WriteLine("MyCustom Routed Event occurred!");
}

In the code above, we create MyControl and raise the MyCustom event when the user clicks. It demonstrates how to connect this event in XAML for handling. When the event occurs, the MyControl_MyCustom method is called to print a message in the debug log.

Routed Events and Delegates

In UWP, Routed Events are implemented through Delegates. Routed Event handlers have specific signatures that are associated with the routed events. Here’s an example using Delegate:

csharp
public delegate void CustomEventHandler(object sender, CustomEventArgs e);
public event CustomEventHandler CustomEvent;

protected virtual void OnCustomEvent(CustomEventArgs e)
{
    CustomEvent?.Invoke(this, e); // Raise the event
}

Using Delegates like this allows for implementing complex logic and sending custom events with additional event data.

Conclusion

Routed Events are a powerful tool that enables efficient handling of user interactions with the user interface in UWP development. We examined how to raise and handle events, create custom events, and utilize Delegates. With this understanding, you can enhance the interface and user experience of your UWP applications.

Now, we hope you will leverage Routed Events to develop better UWP apps. If you have any questions, feel free to ask in the comments!

UWP Development, Objects that can be used as Resources

The Universal Windows Platform (UWP) is a platform for developing applications that run on various devices. Efficient management and utilization of resources in UWP apps are crucial as it helps maximize user experience and streamline the development process. In this article, we will explain the objects that can be utilized as resources in UWP development in detail, facilitating understanding through usage examples and explanations for each object.

1. The Concept of Resources in UWP

A resource is defined as a visual element or a piece of data used in an application. In UWP applications, resources are typically defined and used in XAML files. Resources can be categorized into the following types:

  • Styles: Define the look and feel of UI elements.
  • Templates: Define the structure of UI elements.
  • Brushes: Define colors and gradients.
  • ControlTemplates: Define the layout of custom controls.
  • Resources: Define objects that can be shared commonly.

2. Defining and Using Resources

There are several ways to define resources in UWP. Typically, they are defined within the Page.Resources or Application.Resources section of a XAML file.

2.1. Example of Defining and Using a Style

<Page.Resources>
    <Style x:Key="MyButtonStyle" TargetType="Button">
        <Setter Property="Background" Value="LightBlue"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="16"/>
    </Style>
</Page.Resources>

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

In the above example, a style resource for a button is defined and utilized. The defined style is called using StaticResource.

2.2. Example of Using a Brush Resource

<Page.Resources>
    <SolidColorBrush x:Key="MySolidBrush" Color="Red"/>
</Page.Resources>

<Rectangle Fill="{StaticResource MySolidBrush}" Width="100" Height="100" />

Here, an example is shown where a red SolidColorBrush is defined and used as the Fill property of a Rectangle.

3. Managing Resources

In UWP, resources can be managed in various ways. Not only can you define the design of objects, but you can also change resources dynamically.

3.1. Example of Dynamically Changing a Resource

<Button x:Name="DynamicButton" Content="Click Me!" Click="DynamicButton_Click" />
private void DynamicButton_Click(object sender, RoutedEventArgs e)
{
    var newBrush = new SolidColorBrush(Windows.UI.Colors.Green);
    this.Resources["MySolidBrush"] = newBrush;
}

This code example shows how the color of a brush defined in the resources is changed dynamically upon button click.

4. Using Global Resources

In UWP, you can define global resources that can be used throughout the app via Application.Resources.

4.1. Example of Defining a Global Style

<Application.Resources>
    <Style TargetType="Button">
        <Setter Property="Background" Value="Purple"/>
        <Setter Property="Foreground" Value="White"/>
    </Style>
</Application.Resources>

By defining a global style in this way, the same style can be applied to all buttons in the app.

4.2. Example of Using a Global Resource

<Button Content="Global Styled Button" />

When global resources are defined, all buttons in the app will follow the default style set, without needing to specify a style separately.

5. Utilizing Resource Dictionaries

By utilizing resource dictionaries, resources can be managed systematically. In large applications, as resources grow, it’s beneficial to use separate resource dictionaries to distinguish them.

5.1. Defining a Resource Dictionary

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="SecondaryButtonStyle" TargetType="Button">
        <Setter Property="Background" Value="Teal"/>
        <Setter Property="Foreground" Value="White"/>
    </Style>
</ResourceDictionary>

5.2. Example of Using a Resource Dictionary

<Page.Resources>
    <ResourceDictionary Source="Assets/Styles.xaml"/>
</Page.Resources>

<Button Style="{StaticResource SecondaryButtonStyle}" Content="Secondary Button" />

6. Technical Considerations

There are several considerations when using resources.

  • Scope of Resources: You should be aware of where the scope of resources lies, and define them appropriately.
  • Performance Impact: Incorrectly set resources can impact performance. It is advisable to define resources that can be reused whenever possible.

7. Conclusion

Managing and utilizing resources in UWP development is a very important factor for the performance, maintainability, and enhancement of user experience of applications. This article discussed how to effectively manage resources in UWP through definitions, usage methods, dynamic changes, global resources, and resource dictionary usage. By managing resources well, optimized applications can be developed effectively across various devices.

Additionally, a deep understanding of resources will lead to the development of more specialized and customized applications. It is essential to invest time in cultivating the ability to manage and utilize resources efficiently.

UWP Development, RelativePanel

In UWP (Universal Windows Platform) app development, layout is a very important aspect.
In modern applications where environments vary across different screen sizes and devices,
proper layout management is essential. To assist with this, UWP provides several layout panels.
Among them, RelativePanel is a powerful tool that allows you to set the layout based on the relative position of components.

1. Overview of RelativePanel

RelativePanel is a panel that organizes layout by defining relationships among child elements.
It allows you to place elements based on their relative positions to one another, enabling the implementation of appropriate responsive layouts as screen sizes change.
Each child element can have reference points relative to other child elements, making it easy to manage complex layouts.

2. Key Properties of RelativePanel

  • AlignLeftWithPanel: Aligns the left edge of the element with the left edge of the panel.
  • AlignRightWithPanel: Aligns the right edge of the element with the right edge of the panel.
  • AlignTopWithPanel: Aligns the top edge of the element with the top edge of the panel.
  • AlignBottomWithPanel: Aligns the bottom edge of the element with the bottom edge of the panel.
  • AlignLeftWith: Aligns based on the left edge of a specific element.
  • AlignRightWith: Aligns based on the right edge of a specific element.
  • AlignTopWith: Aligns based on the top edge of a specific element.
  • AlignBottomWith: Aligns based on the bottom edge of a specific element.
  • SetLeftOf: Positions the element to the right of a specific element.
  • SetRightOf: Positions the element to the left of a specific element.
  • SetAbove: Positions the element below a specific element.
  • SetBelow: Positions the element above a specific element.

3. Example of Using RelativePanel

Now, let’s learn about the basic usage of RelativePanel.
In this example, we will create a simple UI that includes a button, a text box, and an image element.

<RelativePanel>
    <TextBlock x:Name="myTextBlock" Text="Hello, RelativePanel!" FontSize="24" />
    <Button x:Name="myButton" Content="Click Me!" />
    <Image x:Name="myImage" Source="Assets/myImage.png" Width="100" Height="100" />
</RelativePanel>

Example Explanation

The code above is a RelativePanel containing three child elements.
The button and image can be personalized based on their relative position to the text block.
You can add the following code to adjust the position of the elements.

<RelativePanel>
    <TextBlock x:Name="myTextBlock" Text="Hello, RelativePanel!" FontSize="24" 
        RelativePanel.AlignLeftWithPanel="True" 
        RelativePanel.AlignTopWithPanel="True" />
        
    <Button x:Name="myButton" Content="Click Me!" 
        RelativePanel.AlignLeftWith="myTextBlock" 
        RelativePanel.SetRightOf="myTextBlock" />
        
    <Image x:Name="myImage" Source="Assets/myImage.png" Width="100" Height="100" 
        RelativePanel.SetBelow="myButton" 
        RelativePanel.AlignLeftWithPanel="True" />
</RelativePanel>

In this code, the TextBlock is positioned at the top left of the panel,
and the Button is set to the right of the TextBlock.
Lastly, the Image is placed below the button.

4. Creating Responsive UI with RelativePanel

RelativePanel is useful for implementing responsive designs even on complex screens.
When developing apps that support various screen sizes, you can specify the relative position of each element to resolve layout issues.
For example, you can enhance the placement of elements as shown below to achieve a more refined design.

<RelativePanel>
    <TextBlock x:Name="titleTextBlock" Text="Welcome to UWP!" FontSize="32" 
        RelativePanel.AlignTopWithPanel="True" 
        RelativePanel.AlignHorizontalCenterWithPanel="True" />
        
    <Button x:Name="startButton" Content="Get Started" 
        RelativePanel.SetBelow="titleTextBlock" 
        RelativePanel.AlignHorizontalCenterWithPanel="True" />

    <Image x:Name="logoImage" Source="Assets/logo.png" Width="200" Height="200" 
        RelativePanel.SetBelow="startButton" 
        RelativePanel.AlignHorizontalCenterWithPanel="True" />
</RelativePanel>

The code above positions the title, start button, and logo image in the horizontal center, providing a consistent UI experience across all screen sizes.

5. Tips and Precautions for Using RelativePanel

  • It is advisable to set maximum and minimum sizes for child elements to control their size.
  • Also, when using complex layouts, performance may be impacted, so it is best to avoid overly complex structures.
  • Nesting multiple RelativePanel instances allows for the creation of more diverse layouts.

6. Conclusion

RelativePanel is a highly effective layout tool in UWP, allowing for easy placement of various elements through their relative positions
and is very useful for implementing responsive design.
By utilizing various properties, you can maximize the functionality of each child element and
improve user experience.
Make good use of these tools to develop attractive and intuitive UIs.

7. Download Code Example

You can download the complete code example from the link below:
UWP RelativePanel Example

I hope this helps in your UWP development journey,
and if you have any questions or comments, feel free to leave them below!
Thank you.

UWP Development, Resource

The Windows Universal Platform (UWP) is a platform for developing applications that run on various Windows 10 devices. When creating UWP applications, resources play a very important role and are essential for the application’s style, layout, and multilingual support. This article will take a detailed look at the concept of resources in UWP development and explain it with actual example code.

1. Overview of Resources in UWP Applications

Resources are a collection of reusable content in an application, and they can exist in various forms, especially as styles, images, strings, and other UI elements. By using resources, you can increase code reusability and make maintenance easier.

1.1 Types of Resources

  • StaticResource: Used to define resources that generally do not change. For example, it is suitable for colors or style definitions that are used repeatedly.
  • DynamicResource: Used to deal with resources that can change during application execution. It is useful in situations like theme changes.
  • Styles: Styles are used to define the visual representation of UI components. This helps to reduce code duplication.
  • Templates: Used to define the layout of UI elements, allowing you to set a custom appearance for specific UI components.

2. Defining UWP Resources

Below is an example showing how to define resources in a XAML file. This example includes defining colors and styles.

<Page.Resources>
    <Color x:Key="PrimaryColor">#FF6200EE</Color>
    <SolidColorBrush x:Key="PrimaryBrush" Color="{StaticResource PrimaryColor}" />
    
    <Style x:Key="ButtonStyle" TargetType="Button">
        <Setter Property="Background" Value="{StaticResource PrimaryBrush}" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="16" />
    </Style>
</Page.Resources>

2.1 Locations of Resources

Resources can be defined in several places. Here are the main locations where resources can be defined:

  • Application.xaml: Defines resources that can be used throughout the application.
  • Page.xaml: Defines resources that can only be used on a specific page.
  • Resources Folder: Manages string resources for multilingual support by adding resource files (.resx).

3. Using Resources

The defined resources can be bound to various elements in XAML. Below is an example of applying a style to a button.

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

3.1 Dynamic Resource Conversion

You can add functionality for users to change themes using dynamic resources. Below is the code for dynamically changing the background color.

<Grid Background="{DynamicResource BackgroundBrush}">

4. Resources for Multilingual Support

Multilingual support is one of the important elements in UWP development. To achieve this, resource dictionaries (.resx files) are used. By defining string resources in separate files, various languages can be supported.

using System.Globalization;
using Windows.ApplicationModel.Resources;

// Example of using string resources
var resourceLoader = ResourceLoader.GetForCurrentView();
string welcomeMessage = resourceLoader.GetString("WelcomeMessage");

4.1 Creating Resource Files

The following is how to add resource files in Visual Studio:

  1. Right-click on the project and select “Add” -> “New Item”.
  2. Select “Resource File” and enter a file name.
  3. Add resource files for each language (e.g., Strings.resx, Strings.fr.resx, etc.).

5. Resource Optimization in UWP

Optimizing resources contributes to improving application performance and reducing load times. It is important to remove unnecessary resources and use only the required resources efficiently.

6. Conclusion

Resources play an important role in managing UI elements and providing multilingual support in UWP applications. By using resources effectively, you can greatly enhance the maintainability and usability of the application. Practice the various resource concepts and examples described in this article to broaden your understanding of UWP development.

7. Additional Resources