UWP Development, Applying Local Resources

In UWP (Universal Windows Platform) development, the ability for apps to access and utilize local resources is very important. Local resources include data provided by users to the app, and methods for effectively utilizing this data are presented. In this article, we will explain how to apply local resources in UWP apps and provide code implementations through several examples.

1. Understanding Local Resources

Local resources may include files, images, videos, audio files, etc., on the user’s device. These resources can be applied in UWP apps in various ways. Local resources can be classified into the following types:

  • File System Resources: Access to files stored in the user’s local storage.
  • Resources from Other Apps: For example, utilizing clipboard or data from other apps.
  • Settings and User Data: Includes app settings or user-defined data.

2. Setting Access to Local Resources

For a UWP app to access the local file system, the necessary features must be set in the app manifest. Open the Package.appxmanifest file and add the required permissions such as Private Networks (Client & Server), Music Library, Pictures Library in the Capabilities tab.

3. Accessing the File System

The most basic way for a UWP app to access the local file system is to use the StorageFile class. Below is an example of how to read and write files.

3.1. Writing a File


using Windows.Storage;

async Task WriteToFile(string content)
{
    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
    StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteTextAsync(sampleFile, content);
}
    

The method above creates a sample.txt file in the application’s local folder and writes the provided content to that file.

3.2. Reading a File


async Task ReadFromFile()
{
    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
    StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
    string content = await FileIO.ReadTextAsync(sampleFile);
    return content;
}
    

This method reads the contents of the sample.txt file in the local folder and returns it.

4. Accessing the Pictures Library

To access the Pictures Library in a UWP app, you need to add the Pictures Library permission. Here’s an example of how to select and display images from the user’s picture library.

4.1. Selecting an Image


async Task PickImageAsync()
{
    var picker = new FileOpenPicker();
    picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    picker.FileTypeFilter.Add(".jpg");
    picker.FileTypeFilter.Add(".png");

    return await picker.PickSingleFileAsync();
}
    

4.2. Displaying the Selected Image


async void DisplayImage(StorageFile file)
{
    if (file != null)
    {
        var stream = await file.OpenAsync(FileAccessMode.Read);
        var bitmapImage = new BitmapImage();
        bitmapImage.SetSource(stream);

        Image imageControl = new Image();
        imageControl.Source = bitmapImage;

        ContentGrid.Children.Add(imageControl); // ContentGrid is the Grid defined in XAML
    }
}
    

This code uses a file picker to allow the user to select a photo and displays the selected image in the app’s UI.

5. Saving and Reading Data

Saving and reading data in JSON format in UWP apps is a common requirement. Below is an example of using JSON files.

5.1. JSON Data Model


public class UserSettings
{
    public string Username { get; set; }
    public int Age { get; set; }
}
    

5.2. Writing JSON Data


async Task SaveUserSettings(UserSettings settings)
{
    var json = JsonConvert.SerializeObject(settings);
    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
    StorageFile settingsFile = await storageFolder.CreateFileAsync("settings.json", CreationCollisionOption.ReplaceExisting);
    
    await FileIO.WriteTextAsync(settingsFile, json);
}
    

5.3. Reading JSON Data


async Task LoadUserSettings()
{
    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
    StorageFile settingsFile = await storageFolder.GetFileAsync("settings.json");
    string json = await FileIO.ReadTextAsync(settingsFile);

    return JsonConvert.DeserializeObject(json);
}
    

6. Conclusion

This article explained how to utilize local resources in UWP development through various examples. Access to local resources is an important factor in enhancing user experience in apps, so it is essential to set the required permissions and provide a user-friendly interface. Accessing local resources is a fundamental part of UWP app development, enabling the diversity and functionality of the app.

7. References

UWP Development, Drag and Drop Events

In Universal Windows Platform (UWP) development, drag and drop events are one of the key features that enhance user interface (UI) interaction. This technology allows users to easily perform various types of interactions, such as moving, adding, or removing objects within the program.

Basics of Drag and Drop Events

Drag and drop involves the action of the user pressing a mouse button to select a specific object, moving it to another location, and then releasing the mouse button. The events that occur during this process can be broadly divided into three types:

  • DragStarting: Occurs when the drag starts.
  • Drop: Occurs when the dragged object is placed at the target location.
  • DragOver: Occurs when the dragged object moves over another object.

Implementing Drag and Drop in UWP

Now let’s look at how to implement drag and drop functionality in a UWP application.

1. Basic Setup

Create a UWP application and open the XAML file to define the UI elements where drag and drop will be applied. Below is an example that includes a Grid and a ListView:

<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">

    <Grid>
        <ListView x:Name="MyListView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" 
                               AllowDrop="True" 
                               DragItemsStarting="MyListView_DragItemsStarting" 
                               Drop="MyListView_Drop" 
                               DragOver="MyListView_DragOver"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

2. Handling the Drag Start Event

To handle the event when dragging starts in the list view, implement the DragItemsStarting event handler in C# code. This handler sets the information for the dragged item.

private void MyListView_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
    e.Data.SetText(e.Items[0].ToString());
    e.Data.RequestedOperation = DataPackageOperation.Move;
}

3. Handling the Drag Over Event

To handle the event when the dragged object moves over another location, implement the DragOver event handler. This handler checks whether dropping is possible.

private void MyListView_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.ContainsText())
    {
        e.AcceptedOperation = DataPackageOperation.Move;
    }
    else
    {
        e.AcceptedOperation = DataPackageOperation.None;
    }
}

4. Handling the Drop Event

Finally, implement the Drop event handler to handle the drop event. Here, the logic to add the dropped item to the list view is written.

private void MyListView_Drop(object sender, DragEventArgs e)
{
    if (e.Data.ContainsText())
    {
        string droppedData = await e.Data.GetTextAsync();
        // Add the dropped item to the list
        myItems.Add(droppedData);
    }
}

Example: Image Drag and Drop

Based on what we just learned, let’s create an example that allows users to drag and drop image files. This example implements the feature for users to add images to the list by dragging.

UI Setup

<Grid>
    <Image x:Name="MyImage" 
           AllowDrop="True" 
           Drop="Image_Drop" 
           DragOver="Image_DragOver" 
           Source="Assets/placeholder.png" />
</Grid>

Implementing Event Handlers

Modify the previously explained drag over and drop event handlers to fit the image.

private async void Image_Drop(object sender, DragEventArgs e)
{
    if (e.Data.ContainsFile())
    {
        var files = await e.Data.GetStorageFilesAsync();
        // Display the file as an image
        var file = files.First();
        var bitmap = new BitmapImage();
        bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
        MyImage.Source = bitmap;
    }
}

Drag Over Response

private void Image_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.ContainsFile())
    {
        e.AcceptedOperation = DataPackageOperation.Copy;
    }
    else
    {
        e.AcceptedOperation = DataPackageOperation.None;
    }
}

Utilizing Drag and Drop

Drag and drop functionality can be utilized in various fields. For example:

  • Changing the priority of task items in task management applications.
  • Changing the location of files in file management applications.
  • Manipulating multiple images in image editing applications.

Conclusion

Drag and drop events are a simple yet powerful technology that can greatly enhance the user experience of UWP applications. They can be implemented in suitable ways for different environments and make interactions with users more natural and intuitive. Utilizing these features allows for the development of more attractive and useful applications.

References

UWP Development, Data Binding and Binding Errors

Data binding in UWP (Universal Windows Platform) development plays a crucial role as a vital link between the user interface (UI) and the data source. Through data binding, synchronization between the UI and data can be managed easily, significantly enhancing the developer’s productivity and improving the maintainability of the code. However, when using data binding, binding errors may occur, and it is important to understand and handle these errors. In this article, we will take a closer look at the concepts of data binding in UWP and binding errors.

1. The Concept of Data Binding

Data binding is a technique that establishes a connection between UI elements and data sources, allowing the UI to be automatically updated when data changes. In UWP, XAML (Extensible Application Markup Language) is primarily used to define the UI, and data binding can link UI elements to data sources.

The main benefits of data binding in UWP are as follows:

  • Improved Productivity: By automatically handling synchronization between the UI and data source, developers can create apps more easily.
  • Simplified Code: Using data binding reduces the amount of code needed to connect UI elements and data sources.
  • Support for MVVM Pattern: Data binding helps in easily applying the MVVM (Model-View-ViewModel) architectural pattern.

2. Types of Data Binding

UWP supports various types of data binding. The main types of binding are as follows:

2.1 One-Way Binding

One-way binding updates the UI based on changes in the data source, but changes in the UI do not affect the data source. This is mainly used in read-only situations.



2.2 Two-Way Binding

Two-way binding reflects changes on both the data source and the UI. Changes made by the user in the UI affect the data source, and changes in the data source are also reflected in the UI. This is commonly used in input fields.



2.3 OneTime Binding

OneTime binding reads the value from the data source only once when the binding is set. Subsequent changes in the data source are not reflected in the UI.



3. Data Models for Data Binding

To use data binding in UWP, a data model needs to be defined. This model is generally implemented as a C# class and should implement the INotifyPropertyChanged interface to support property change notifications. This allows changes in the data to be reflected in the UI.


using System.ComponentModel;

public class User : INotifyPropertyChanged
{
    private string _name;
    private string _username;

    public string Name
    {
        get { return _name; }
        set 
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    public string Username
    {
        get { return _username; }
        set 
        {
            _username = value;
            OnPropertyChanged("Username");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

4. Example of Using Data Binding

Now let’s look at how to utilize data binding by creating a simple UWP application.

4.1 XAML File




    
        
            
            

            
            

            
            
        
    

4.2 Code Behind File


using Windows.UI.Xaml.Controls;

namespace MyApp
{
    public sealed partial class MainPage : Page
    {
        public User CurrentUser { get; set; }

        public MainPage()
        {
            this.InitializeComponent();
            CurrentUser = new User() { Name = "John Doe", Username = "john" };
            this.DataContext = CurrentUser;
        }
    }
}

In this example, we configured a UI to receive user input for both username and real name. The values entered by the user are automatically bound to the CurrentUser object.

5. Handling Binding Errors

When using data binding, binding errors may occur, typically due to the following reasons:

  • Data Source is null: An error occurs if the data source is null at the time of setting the binding.
  • Property Name Error: An error occurs if the name of the bound property is incorrect or if the property does not exist in the data source.
  • Type Mismatch: An error may occur if the type of the UI element’s property does not match the type of the data source.

There are various methods to handle binding errors. One of the simplest methods is to use Debug.WriteLine to log the error.


BindingOperations.SetBinding(myTextBlock, TextBlock.TextProperty, myBinding);
Debug.WriteLine($"Binding Error: {bindingExpression.Status}");

Additionally, binding errors can be handled through the BindingFailed event.

6. Conclusion

Data binding in UWP is an essential element that provides seamless interaction between users and applications. Through data binding technology, the UI can be dynamically updated and user input can be easily managed. However, when using data binding, it is important to be aware that binding errors may occur and to handle them properly. In this article, we discussed the concepts of data binding, examples, and how to handle binding errors. We hope this foundational knowledge supports your UWP application development.

UWP Development, Data Binding

1. Introduction

UWP (Universal Windows Platform) is a platform for creating applications that run on all devices
with Windows 10 and later. UWP provides a modern user interface and is designed to run across various devices.
Additionally, the concept of data binding plays an important role in UWP development. With data binding, developers can
connect data sources to UI elements, enabling the development of more efficient and dynamic applications.

2. The Concept of Data Binding

Data Binding is a technique that establishes a connection between UI elements and data sources. By using data binding, the
UI can immediately respond to changes in the data source, allowing developers to easily manage the interaction between UI and data logic.
It typically provides a connection between the View and Model, making it suitable for the MVVM (Model-View-ViewModel) architecture.

2.1. Types of Data Binding

In UWP, data binding is primarily offered in two forms: one-way binding and two-way binding.

  • One-Way Binding: Used to represent the data from the data source (model) in the UI.
    When the data changes, the UI reflects those changes, but modifications in the UI do not affect the data source.
  • Two-Way Binding: Allows for two-way synchronization between the UI and data source.
    When data is changed in the UI, the data source is automatically updated.

3. Implementing Data Binding in UWP

Now, let’s look at how to implement data binding in a UWP application.
As an example, we will create an application to manage a simple contact list.

4. Understanding the MVVM Pattern

MVVM stands for Model-View-ViewModel, a widely used pattern for data handling in UWP applications.
By using the MVVM pattern, code reusability increases, and testability improves.

  • Model: Manages data and business logic.
  • View: UI elements presented to the user. Defined using XAML.
  • ViewModel: Acts as an interface between the View and Model. It provides the data and commands used in the View.

5. Writing Example Code

Below is an example code for a simple UWP application that manages a contact list using the MVVM pattern.

5.1. Creating the Model Class

public class Contact
{
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
}
            

5.2. Creating the ViewModel Class

using System.Collections.ObjectModel;
using System.ComponentModel;

public class ContactViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Contact> Contacts { get; set; }

    public ContactViewModel()
    {
        Contacts = new ObservableCollection<Contact>();
        LoadContacts();
    }

    private void LoadContacts()
    {
        Contacts.Add(new Contact { Name = "John Doe", PhoneNumber = "123-456-7890" });
        Contacts.Add(new Contact { Name = "Jane Smith", PhoneNumber = "987-654-3210" });
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
            

5.3. Implementing the View (XAML)

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

    <Grid>
        <ListView ItemsSource="{Binding Contacts}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}"/>
                        <TextBlock Text="{Binding PhoneNumber}"/>
                    </StackPanel>
                </DataTemplate>
            <ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>
            

5.4. Configuring MainPage.xaml.cs

using Windows.UI.Xaml.Controls;

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = new ContactViewModel();
    }
}
            

6. Advantages of Data Binding

Data binding offers

  • Automatic synchronization between UI and data, enhancing development productivity.
  • Reduces coupling of code and improves maintainability through the MVVM pattern.
  • Makes testing and debugging easier, enhancing overall code quality.

7. Conclusion

Data binding in UWP is a very important concept in modern application development.
This technology allows for synchronizing UI elements with data and utilizing an efficient MVVM architecture.
Based on what has been introduced in this article, I hope your UWP development experience becomes even more enriching.
Furthermore, you can experiment with various features and techniques of data binding to enhance your applications.

UWP Development, Data Validation – Complete Item Comparison Validation

Universal Windows Platform (UWP) development is a powerful framework for creating applications that run on various Windows 10 devices. UWP applications prioritize user experience, and data validation is an essential component to ensure the quality of the application. This article will explore the importance of data validation and how to implement full item comparison validation.

1. Importance of Data Validation

Data validation is the process of verifying that the data entered by the user meets specific conditions. Through the validation process, accurate input is required from the user, minimizing errors due to incorrect data entry.

Data validation is particularly important in UWP applications, as they handle complex business logic that relies on user interaction and requires data accuracy. By implementing data validation, the stability and reliability of the application can be increased.

2. Concept of Full Item Comparison Validation

Full item comparison validation is the process of verifying that all items in a given dataset satisfy certain rules or conditions by comparing them. Generally, users will input multiple data points, and it is necessary to verify the consistency of this data.

For example, you can think of validating whether the value entered by the user in the password field matches the value in the password confirmation field in a user registration form. Such validation logic focuses on confirming whether the entire items compare to meet the conditions.

3. Implementing Data Validation in UWP

3.1. Setting Up Basic Structure

To develop a UWP application, use Visual Studio to create a new UWP project. Set it up to receive user input with a basic form template.

Sample XAML Code

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

    <Grid>
        <TextBox x:Name="PasswordTextBox" PlaceholderText="Password" PasswordChar="*" />
        <TextBox x:Name="ConfirmPasswordTextBox" PlaceholderText="Confirm Password" PasswordChar="*" />
        <Button Content="Validate" Click="ValidateButton_Click" />
        <TextBlock x:Name="ValidationMessage" />
    </Grid>
</Page>

4. Implementing Full Item Comparison Validation Logic

After the user has entered the password and confirmation password fields, implement the logic to check if these two fields match when the validate button is clicked. Define the ValidateButton_Click method to compare the entered values.

Sample C# Code

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

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

        private void ValidateButton_Click(object sender, RoutedEventArgs e)
        {
            string password = PasswordTextBox.Text;
            string confirmPassword = ConfirmPasswordTextBox.Text;

            if (password == confirmPassword)
            {
                ValidationMessage.Text = "Passwords match.";
            }
            else
            {
                ValidationMessage.Text = "Passwords do not match.";
            }
        }
    }
}

5. Enhancing User Experience

After successful data validation, it is important to provide additional feedback for user convenience. Depending on the validation result, appropriate guidance messages can be displayed or visual feedback can be given to the user through the UI.

6. Refactoring for Data Validation

Refactoring the validation logic can enhance reusability and maintainability. If multiple items need validation, separate them into individual methods to handle each validation item.

Refactored C# Code

private bool ValidatePasswords(string password, string confirmPassword)
{
    return password == confirmPassword;
}

private void ValidateButton_Click(object sender, RoutedEventArgs e)
{
    string password = PasswordTextBox.Text;
    string confirmPassword = ConfirmPasswordTextBox.Text;

    if (ValidatePasswords(password, confirmPassword))
    {
        ValidationMessage.Text = "Passwords match.";
    }
    else
    {
        ValidationMessage.Text = "Passwords do not match.";
    }
}

7. Implementing Exception Handling

When performing validation, it is necessary to handle appropriate exceptions if the input values are null or empty. By managing these exceptions, a better user experience can be provided.

Sample Code with Exception Handling

private void ValidateButton_Click(object sender, RoutedEventArgs e)
{
    string password = PasswordTextBox.Text;
    string confirmPassword = ConfirmPasswordTextBox.Text;

    if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(confirmPassword))
    {
        ValidationMessage.Text = "Please enter a password.";
        return;
    }

    if (ValidatePasswords(password, confirmPassword))
    {
        ValidationMessage.Text = "Passwords match.";
    }
    else
    {
        ValidationMessage.Text = "Passwords do not match.";
    }
}

8. Optimizing Data Validation

When considering the performance of the application, it is also necessary to optimize the data validation process. For example, passwords often need to meet certain criteria. This allows for a more nuanced validation process and improved performance.

Optimized Password Validation Method

private bool ValidatePasswordCriteria(string password)
{
    // Password criteria: At least 8 characters, includes digits, includes special characters, etc.
    if (password.Length < 8 || !password.Any(char.IsDigit) || !password.Any(ch => !char.IsLetterOrDigit(ch)))
    {
        ValidationMessage.Text = "Password must be at least 8 characters long and include digits and special characters.";
        return false;
    }

    return true;
}

9. Conclusion

This Universal Windows Platform (UWP) development tutorial covered data validation, particularly full item comparison validation. Data validation is an important process that ensures the accuracy and consistency of user input, thereby providing a better experience for users.

By effectively implementing data validation in UWP applications, the reliability of the application can be enhanced, offering a safer environment. We hope you will improve your development skills by learning various validation logic alongside the example codes.

Continuous learning and practice will enhance your programming skills. The next tutorial will also cover useful UWP development techniques, so we appreciate your interest.