Skip to content

Commit

Permalink
Update Framework Databinding How-To (#1868)
Browse files Browse the repository at this point in the history
* Add data object to .NET WPF data binding article

* Rewrite Framework databinding how-to

* Fix linter settings

* Adjust intro and fix linter err

* Disable number linter for now

* Add VB

* Update some wording

* Call out .net framework in article

* Add .NET version

* Forgot to add new article lolz

* Fix links

* Update dotnet-desktop-guide/net/wpf/data/how-to-create-a-simple-binding.md

Co-authored-by: David Pine <[email protected]>

* Update dotnet-desktop-guide/net/wpf/data/how-to-create-a-simple-binding.md

Co-authored-by: David Pine <[email protected]>

* Add changes from other file

---------

Co-authored-by: David Pine <[email protected]>
  • Loading branch information
adegeo and IEvangelist authored Jul 26, 2024
1 parent 8019513 commit 5e14e82
Show file tree
Hide file tree
Showing 48 changed files with 1,359 additions and 20 deletions.
1 change: 1 addition & 0 deletions .markdownlint-cli2.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"MD026": false,
// Cannot be enabled due to sequential Note blocks
"MD028": false,
"MD030": false,
"MD033": {
"allowed_elements": [
"a",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,83 @@
---
title: "How to: Create a Simple Binding"
description: Create a simple binding for your applications through this how-to example in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
title: "How to create a data binding"
description: Create a simple binding for your applications through this how-to example in Windows Presentation Foundation (WPF) and .NET Framework.
ms.date: 07/24/2024
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "simple binding [WPF], creating"
- "data binding [WPF], creating simple bindings"
- "binding data [WPF], creating"
ms.assetid: 69b80f72-6259-44cb-8294-5bdcebca1e08
#customer intent: As a devleoper, I want to create a binding so that I can present information in a UI
---
# How to: Create a Simple Binding

This example shows you how to create a simple <xref:System.Windows.Data.Binding>.

## Example

In this example, you have a `Person` object with a string property named `PersonName`. The `Person` object is defined in the namespace called `SDKSample`.

The highlighted line that contains the `<src>` element in the following example instantiates the `Person` object with a `PersonName` property value of `Joe`. This is done in the `Resources` section and assigned an `x:Key`.

[!code-xaml[SimpleBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/SimpleBinding/CSharp/Page1.xaml?highlight=9,37)]

The highlighted line that contains the `<TextBlock>` element then binds the <xref:System.Windows.Controls.TextBlock> control to the `PersonName` property. As a result, the <xref:System.Windows.Controls.TextBlock> appears with the value "Joe".

## See also

# How to create a data binding

This article describes how to create a binding XAML. The example uses a data object that represents an employee at a company. This data object is bound to a XAML window that uses `TextBlock` controls to list the employee's details. You'll create a UI that looks like the following image:

:::image type="content" source="media/how-to-create-a-simple-binding/preview.png" alt-text="A WPF window that shows details about an employee, such as their first name, last name, title, hire date, and salary.":::

To learn more about data binding, see [Data binding overview in WPF](data-binding-overview.md).

## Create a data object

In this example, an employee is used as the data object that the UI is bound to.

1. Add a new class to your project and name it `Employee`.
1. Replace the code with the following snippet:

:::code language="csharp" source="./snippets/how-to-create-a-simple-binding/csharp/Employee.cs":::
:::code language="vb" source="./snippets/how-to-create-a-simple-binding/vb/Employee.vb":::

The employee data object is a simple class that describes an employee:

- The first and last name of the employee.
- The date the employee was hired.
- The employee's company title.
- How much income the employee earns.

## Bind to a data object

The following XAML demonstrates using the `Employee` class as a data object. The root element's `DataContext` property is bound to a static resource declared in the XAML. The individual controls are bound to the properties of the `Employee`.

1. Add a new **Window** to the project and name it `EmployeeView`
1. Replace the XAML with the following snippet:

> [!IMPORTANT]
> The following snippet is taken from a C# project. If you're using Visual Basic, the `x:Class` should be declared without the `ArticleSample` namespace. You can see what the Visual Basic version looks like [here](https://github.com/dotnet/docs-desktop/blob/main/dotnet-desktop-guide/framework/wpf/data/snippets/how-to-create-a-simple-binding/vb/EmployeeView.xaml).
:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" highlight="7-9,33-37,43":::

The namespace of the code won't match your project's namespace, unless you created a project named **ArticleSample**. You can copy and paste the `Window.Resources` and root element (`StackPanel`) into you're **MainWindow** if you created a new project.

To better understand how the previous XAML is using data binding, consider the following points:

- A XAML resource is used to create an instance of the `Employee` class.

Typically the data object is passed to or associated with the Window. This example hardcodes the employee for demonstration purposes.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="6-10":::

- The root element (`StackPanel`) has its data context set to the hardcoded `Employee` instance.

The child elements inherit their `DataContext` from the parent, unless explicitly set.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="11":::

- The properties of the `Employee` instance are bound to the `TextBlock` controls.

The `Binding` doesn't specify a `BindingSource`, so the `DataContext` is used as the source.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="33-37":::

- A `TextBox` control is bound with `TwoWay` mode, allowing the `TextBox` to change the `Employee.Salary` property.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="43":::

## Related content

- [Data Binding Overview](data-binding-overview.md)
- [How to: Create a Binding in Code](how-to-create-a-binding-in-code.md)
- [How-to Topics](data-binding-how-to-topics.md)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Application x:Class="ArticleSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleSample"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace ArticleSample
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.ComponentModel;

namespace ArticleSample
{
public class Employee : INotifyPropertyChanged
{
private decimal _salary;
public event PropertyChangedEventHandler PropertyChanged;

public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public DateTime HireDate { get; set; }

public decimal Salary
{
get => _salary;
set
{
_salary = value;

// Support TwoWay binding
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Salary)));
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<Window x:Class="ArticleSample.EmployeeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleSample"
Title="" Height="250" Width="300">
<Window.Resources>
<local:Employee x:Key="EmployeeExample" FirstName="Niki" LastName="Demetriou"
HireDate="2022-02-16" Salary="5012.00"
Title="Content Artist" />
</Window.Resources>
<StackPanel DataContext="{StaticResource EmployeeExample}">
<Label FontSize="32">Employee</Label>
<Border BorderBrush="Gray" BorderThickness="2" />
<Grid Grid.Row="1" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<TextBlock Text="First Name:" Grid.Row="0" Margin="0,0,10,0" />
<TextBlock Text="Last Name:" Grid.Row="1" />
<TextBlock Text="Title:" Grid.Row="2" />
<TextBlock Text="Hire Date:" Grid.Row="3" />
<TextBlock Text="Salary" Grid.Row="4" />

<TextBlock Text="{Binding FirstName}" Grid.Row="0" Grid.Column="1" />
<TextBlock Text="{Binding LastName}" Grid.Row="1" Grid.Column="1" />
<TextBlock Text="{Binding Title}" Grid.Row="2" Grid.Column="1" />
<TextBlock Text="{Binding HireDate, StringFormat=d}" Grid.Row="3" Grid.Column="1" />
<TextBlock Text="{Binding Salary, StringFormat=C0}" Grid.Row="4" Grid.Column="1" />
</Grid>
<Border BorderBrush="Gray" BorderThickness="2" />

<StackPanel Margin="5,10" Orientation="Horizontal">
<TextBlock Text="Change Salary:" Margin="0,0,10,0" />
<TextBox Text="{Binding Salary, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat=C0}" Width="100" />
</StackPanel>
</StackPanel>
</Window>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ArticleSample
{
/// <summary>
/// Interaction logic for EmployeeView.xaml
/// </summary>
public partial class EmployeeView : Window
{
public EmployeeView()
{
InitializeComponent();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Window x:Class="ArticleSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ArticleSample"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel Margin="5">
<Button x:Name="Employee" Content="Employee" Margin="5" Click="Employee_Click" />
</StackPanel>
</Window>
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ArticleSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Employee_Click(object sender, RoutedEventArgs e)
{
EmployeeView window = new EmployeeView();
window.ShowDialog();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netframework4.8.1</TargetFramework>
<UseWpf>true</UseWpf>
<LangVersion>8.0</LangVersion>
<RootNamespace>ArticleSample</RootNamespace>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8.1" />
</startup>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Application x:Class="Application"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleSample"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Class Application

' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
' can be handled in this file.

End Class
Loading

0 comments on commit 5e14e82

Please sign in to comment.