Add how to bind enum article (#1056)

* add how to article

* Fix lint

* Fix the code example

* Add missing code

* Update how-to-bind-to-an-enumeration.md

* Update dotnet-desktop-guide/net/wpf/data/how-to-bind-to-an-enumeration.md

Co-authored-by: Tom Dykstra <[email protected]>

Co-authored-by: Tom Dykstra <[email protected]>
This commit is contained in:
Andy (Steve) De George
2021-05-06 08:03:42 -07:00
committed by GitHub
co-authored by Tom Dykstra
parent dd902d2e9c
commit 3885aab154
21 changed files with 380 additions and 0 deletions
@@ -0,0 +1,64 @@
---
title: How to bind to an enumeration
description: Learn how to use data binding to bind an enumeration to a collection object in XAML and in code for Windows Presentation Foundation.
author: adegeo
ms.author: adegeo
ms.date: 04/30/2021
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "binding data [WPF], enumeration"
- "data binding [WPF], enumeration"
- "enumeration [WPF]"
---
# How to bind to an enumeration (WPF .NET)
This example shows how to bind to an enumeration. Unfortunately there isn't a direct way to use an enumeration as a data binding source. However, the <xref:System.Enum.GetValues(System.Type)?displayProperty=nameWithType> method returns a collection of values. These values can be wrapped in an <xref:System.Windows.Data.ObjectDataProvider> and used as a data source.
The <xref:System.Windows.Data.ObjectDataProvider> type provides a convenient way to create an object in XAML and use it as a data source.
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
## Reference the enumeration
Use the <xref:System.Windows.Data.ObjectDataProvider> type to wrap an array of enumeration values provided by the enumeration type itself.
01. Create a new `ObjectDataProvider` as a XAML resource, either in your application XAML or the XAML of the object you're working with. This example uses a window and creates the `ObjectDataProvider` with a resource key of `EnumDataSource`.
:::code language="xaml" source="./snippets/how-to-bind-to-an-enumeration/csharp/BindEnum.xaml" id="Resources":::
In this example, the `ObjectDataProvider` uses three properties to retrieve the enumeration:
| Property | Description |
|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ObjectType` | The type of object to be returned by the data provider. In this example, <xref:System.Enum?displayProperty=fullName>. The `sys:` XAML namespace is mapped to `System`. |
| `MethodName` | The name of the method to run on the `System.Enum` type. In this example, <xref:System.Enum.GetValues%2A?displayProperty=nameWithType>. |
| `MethodParameters` | A collection of values to provide to the `MethodName` method. In this example, the method takes the `System.Type` of the enumeration. |
Effectively, the XAML is breaking down a method call, method name, parameters, and the return type. The `ObjectDataProvider` configured in the previous example is the equivalent of the following code:
:::code language="csharp" source="./snippets/how-to-bind-to-an-enumeration/csharp/BindEnum.xaml.cs" id="EnumGetValues":::
:::code language="vb" source="./snippets/how-to-bind-to-an-enumeration/vb/BindEnum.xaml.vb" id="EnumGetValues":::
02. Reference the `ObjectDataProvider` resource. The following XAML lists the enumeration values in a <xref:System.Windows.Controls.ListBox> control:
:::code language="xaml" source="./snippets/how-to-bind-to-an-enumeration/csharp/BindEnum.xaml" id="ListBox":::
## Full XAML
The following XAML code represents a simple window that does the following:
01. Wraps the <xref:System.Windows.HorizontalAlignment> enumeration in a <xref:System.Windows.Data.ObjectDataProvider> data source as a resource.
01. Provides a <xref:System.Windows.Controls.ListBox> control to list all enumeration values.
01. Binds a <xref:System.Windows.Controls.Button> control's <xref:System.Windows.FrameworkElement.HorizontalAlignment> property to the selected item in the `ListBox`.
:::code language="xaml" source="./snippets/how-to-bind-to-an-enumeration/csharp/BindEnumFull.xaml":::
## See also
- [Data binding overview](index.md)
- [Binding sources overview](binding-sources-overview.md)
- [StaticResource Markup Extension](../../../framework/wpf/advanced/staticresource-markup-extension.md)
- [An alternative way to bind to an enumeration](https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/)
@@ -0,0 +1,9 @@
<Application x:Class="ArticleExample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleExample"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace ArticleExample
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
@@ -0,0 +1,10 @@
using System.Windows;
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
@@ -0,0 +1,31 @@
<Window x:Class="ArticleExample.BindEnum"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
Title="Enum binding">
<!--<Resources>-->
<Window.Resources>
<ObjectDataProvider x:Key="EnumDataSource"
ObjectType="{x:Type sys:Enum}"
MethodName="GetValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="HorizontalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<!--</Resources>-->
<!--<Content>-->
<StackPanel Width="300" Margin="10">
<TextBlock>Choose the HorizontalAlignment value of the Button:</TextBlock>
<!--<ListBox>-->
<ListBox Name="myComboBox" SelectedIndex="0"
ItemsSource="{Binding Source={StaticResource EnumDataSource}}"/>
<!--</ListBox>-->
<Button Content="I'm a button"
HorizontalAlignment="{Binding ElementName=myComboBox, Path=SelectedItem}" />
</StackPanel>
<!--</Content>-->
</Window>
@@ -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.Shapes;
namespace ArticleExample
{
/// <summary>
/// Interaction logic for BindEnum.xaml
/// </summary>
public partial class BindEnum : Window
{
public BindEnum()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//<EnumGetValues>
var enumDataSource = System.Enum.GetValues(typeof(System.Windows.HorizontalAlignment));
//</EnumGetValues>
}
}
}
@@ -0,0 +1,26 @@
<Window x:Class="ArticleExample.BindEnumFull"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
Title="Enum binding">
<Window.Resources>
<ObjectDataProvider x:Key="EnumDataSource"
ObjectType="{x:Type sys:Enum}"
MethodName="GetValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="HorizontalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<StackPanel Width="300" Margin="10">
<TextBlock>Choose the HorizontalAlignment value of the Button:</TextBlock>
<ListBox Name="myComboBox" SelectedIndex="0"
ItemsSource="{Binding Source={StaticResource EnumDataSource}}"/>
<Button Content="I'm a button"
HorizontalAlignment="{Binding ElementName=myComboBox, Path=SelectedItem}" />
</StackPanel>
</Window>
@@ -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 ArticleExample
{
/// <summary>
/// Interaction logic for BindEnumFull.xaml
/// </summary>
public partial class BindEnumFull : Window
{
public BindEnumFull()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,14 @@
<Window x:Class="ArticleExample.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:ArticleExample"
mc:Ignorable="d"
SizeToContent="WidthAndHeight"
Title="Examples">
<StackPanel Width="200" Margin="35">
<Button Click="Button1_Click">Bind to enum</Button>
</StackPanel>
</Window>
@@ -0,0 +1,33 @@
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 ArticleExample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
new BindEnum().ShowDialog();
}
}
}
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArticleExample
{
enum PrimaryColors
{
Red,
Yellow,
Blue
}
}
@@ -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:ArticleExampleVB"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
@@ -0,0 +1,6 @@
Class Application
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
' can be handled in this file.
End Class
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<RootNamespace>ArticleExampleVB</RootNamespace>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Import Include="System.Windows" />
<Import Include="System.Windows.Controls" />
<Import Include="System.Windows.Data" />
<Import Include="System.Windows.Documents" />
<Import Include="System.Windows.Input" />
<Import Include="System.Windows.Media" />
<Import Include="System.Windows.Media.Imaging" />
<Import Include="System.Windows.Navigation" />
<Import Include="System.Windows.Shapes" />
</ItemGroup>
</Project>
@@ -0,0 +1,11 @@
Imports System.Windows
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
'1st parameter: where theme specific resource dictionaries are located
'(used if a resource is not found in the page,
' or application resource dictionaries)
'2nd parameter: where the generic resource dictionary is located
'(used if a resource is not found in the page,
'app, and any theme specific resource dictionaries)
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
@@ -0,0 +1,12 @@
<Window x:Class="BindEnum"
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:ArticleExampleVB"
mc:Ignorable="d"
Title="BindEnum" Height="450" Width="800">
<Grid>
</Grid>
</Window>
@@ -0,0 +1,7 @@
Public Class BindEnum
Public Sub Method1()
'<EnumGetValues>
Dim enumDataSource = System.Enum.GetValues(GetType(System.Windows.HorizontalAlignment))
'</EnumGetValues>
End Sub
End Class
@@ -0,0 +1,12 @@
<Window x:Class="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:ArticleExampleVB"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
@@ -0,0 +1,7 @@
Class MainWindow
Public Sub Method1()
'<EnumGetValues>
Dim enumValues = System.Enum.GetValues(GetType(System.Windows.HorizontalAlignment))
'</EnumGetValues>
End Sub
End Class
+5
View File
@@ -55,6 +55,11 @@ items:
href: data/binding-declarations-overview.md
- name: Binding sources
href: data/binding-sources-overview.md
items:
- name: Common tasks
items:
- name: Bind to an enumeration
href: data/how-to-bind-to-an-enumeration.md
- name: Systems
expanded: true
items: