# Data Binding

Data binding allows you to establish a link between the UI and the underlying business logic and to keep them synchronized. This means that when a value is changed in the business layer, that change is automatically populated to the UI and vice versa. Of course, in order for this to work, you have to implement the proper notification or to use objects that have already implemented it.

**RadContextMenu** can be used in two modes:

* **Data bound mode** - set **RadContextMenu.ItemsSource** and **RadContextMenu** will automatically display the provided items.

* **Manual mode** - add your items manually to the **RadContextMenu.Items** collection.

## Inherit the Data Context

By default, the **RadContextMenu** inherits the `DataContext` of its parent element. To prevent this behavior, set `InheritDataContext` to `False`.

**Prevent Data Context Inheritance**

```XAML
<telerik:RadContextMenu xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
                        InheritDataContext="False" />
```

## Supported Data Sources

You can bind **RadContextMenu** to the following types of data sources:

* <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerable" target="_blank">IEnumerable</a> - supports simple iteration of a collection. See the Microsoft Learn article for more information.

* <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.icollection" target="_blank">ICollection</a> - extends <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerable" target="_blank">IEnumerable</a> and supports size, enumerator, and synchronization methods for collections.

* <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.ilist" target="_blank">IList</a> - extends <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.icollection" target="_blank">ICollection</a> and is the base class for lists.

## Binding to a Collection

Set the **ItemsSource** property to bind the **RadContextMenu** to a collection exposed by the data context.

**Bind RadContextMenu to a Collection**

```XAML
<TextBox xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
		 Width="200"
		 ContextMenu="{x:Null}">
	<telerik:RadContextMenu.ContextMenu>
		<telerik:RadContextMenu ItemsSource="{Binding MenuItems}"
								DisplayMemberPath="Text" />
	</telerik:RadContextMenu.ContextMenu>
</TextBox>
```

The `MenuItems` collection is supplied by the data context of the view.

For each item in the collection, a container of type **RadMenuItem** is created. By using the **ItemTemplate**, **ItemContainerStyle** and **TemplateSelectors** you can control the appearance of the dynamically created items. Besides the **ItemTemplate** property, you could use the **DisplayMemberPath** property, as shown above, for controlling the appearance of the created items.

> tip If neither the **DisplayMemberPath** nor the **ItemTemplate** are set, then the content of the item would be set to the value returned by the **ToString()** method of the business object.

## Change Notification Support

If you want collection changes to appear automatically in the **RadMenuItems**, the collection must implement the **INotifyCollectionChanged** interface. WPF provides a built-in collection that implements the **INotifyCollectionChanged** interface: the generic **ObservableCollection<T>**. To get the full benefit from change notification, custom business objects must implement the **INotifyPropertyChanged** interface.

> tip Consider using **ObservableCollection<T>** or one of the other existing collection classes like **List<T>**, **Collection<T>**, instead of implementing your own collection. If the scenario requires a custom collection to be implemented, use the **IList** interface, which provides individual access by index to its items and the best performance.

## Binding to Hierarchical Data

The data displayed in the **RadContextMenu** can have a hierarchical structure (similar to the **RadTreeView**). This means that each item may come with a set of items on its own. For that reason you have to use the **ItemContainerStyle**. This section will walk you through the most important steps in creating, configuring and applying an **ItemContainerStyle** to your **RadContextMenu**.

This tutorial uses the following sample class:

**Define the MenuItem Class**

```C#
public class MenuItem
{
    public MenuItem()
    {
        this.SubItems = new ObservableCollection<MenuItem>();
    }
    public string Text
    {
        get;
        set;
    }
    public Uri IconUrl
    {
        get;
        set;
    }
    public bool IsSeparator
    {
        get;
        set;
    }
    public ICommand Command
    {
        get;
        set;
    }
    public ObservableCollection<MenuItem> SubItems
    {
        get;
        set;
    }
}
```

The **MenuItem** class holds the information for the menu items.

* **Text**: Represents the text value for the item.

* **IconUrl**: Represents the URL of the image that represents the icon of the menu item.

* **SubItems**: A collection of the sub menu items of the current menu item.

* **IsSeparator**: Indicates whether the item is a separator.

> tip To learn more about the separator items and the **RadMenuItems**, please take a look at the [RadMenu help content](https://www.telerik.com/products/wpf/documentation/controls/radmenu/overview).

Next, create a method to generate the sample data to populate the **RadContextMenu**:

**Generate Menu Items**

```C#
public ObservableCollection<MenuItem> GetMenuItems()
{
    ObservableCollection<MenuItem> items = new ObservableCollection<MenuItem>();
    MenuItem copyItem = new MenuItem()
    {
        IconUrl = new Uri("Images/copy.png", UriKind.Relative),
        Text = "Copy",
    };
    items.Add(copyItem);
    MenuItem pasteItem = new MenuItem()
    {
        IconUrl = new Uri("Images/paste.png", UriKind.Relative),
        Text = "Paste",
    };
    items.Add(pasteItem);
    MenuItem cutItem = new MenuItem()
    {
        IconUrl = new Uri("Images/cut.png", UriKind.Relative),
        Text = "Cut",
    };
    items.Add(cutItem);
    MenuItem separatorItem = new MenuItem()
    {
        IsSeparator = true
    };
    items.Add(separatorItem);
    MenuItem selectAllItem = new MenuItem()
    {
        Text = "Select All"
    };
    items.Add(selectAllItem);

    return items;
}
```

Finally, set the generated collection as the **ItemsSource** of the control in the view constructor.

**Set the RadContextMenu ItemsSource**

```C#
public MainWindow()
{
    this.InitializeComponent();
    this.radContextMenu.ItemsSource = this.GetMenuItems();
}
```

The `ItemsSource` binding creates the menu items from the generated collection.

Here is a sample **Style** used to visualize the items in the **RadContextMenu** control.

**Define the Menu Item Style**

```XAML
<Style xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" x:Key="MenuItemStyle" TargetType="telerik:RadMenuItem">
    <Setter Property="Icon" Value="{Binding IconUrl}"/>
    <Setter Property="IconTemplate">
        <Setter.Value>
            <DataTemplate>
                <Image Source="{Binding}" Stretch="None"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="IsSeparator" Value="{Binding IsSeparator}"/>
    <Setter Property="Header" Value="{Binding Text}"/>
    <Setter Property="ItemsSource" Value="{Binding SubItems}"/>
    <Setter Property="Command" Value="{Binding Command}"/>
</Style>
```

> tip If you use [NoXaml](https://www.telerik.com/products/wpf/documentation/styling-and-appearance/xaml-vs-noxaml) assemblies, set the BasedOn property to the default style: `BasedOn="{StaticResource RadMenuItemStyle}"`.

> note When setting the **ItemTemplate** or **ItemContainerStyle** properties of the **RadContextMenu**, they will get inherited in the hierarchy, unless they are not explicitly set.

In order to use the created style with the **RadContextMenu** control, set its **ItemContainerStyle** property.

**Apply the ItemContainerStyle**

```XAML
<TextBox xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
         Width="200" VerticalAlignment="Center" ContextMenu="{x:Null}">
    <telerik:RadContextMenu.ContextMenu>
        <telerik:RadContextMenu x:Name="radContextMenu" ItemContainerStyle="{StaticResource MenuItemStyle}" />
    </telerik:RadContextMenu.ContextMenu>
</TextBox>
```

The following image shows the final result.

> caption RadContextMenu populated with data

![WPF RadContextMenu populated with data](https://www.telerik.com/products/wpf/documentation/assets/6f290fc0d7a3f567ae6a4882f8c57379/radcontextmenu_populating_with_data_dynamic_items_02.png)

## Adding Items Manually

To use manual mode, add **RadMenuItem** objects to the **RadContextMenu**.

**Add RadMenuItems Manually**

```XAML
<telerik:RadContextMenu xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
	<telerik:RadMenuItem Header="Copy" />
	<telerik:RadMenuItem Header="Paste" />
</telerik:RadContextMenu>
```

## See Also

* [Getting Started](https://www.telerik.com/products/wpf/documentation/controls/radcontextmenu/getting-started)

* [Item Template and Style Selectors](https://www.telerik.com/products/wpf/documentation/controls/radcontextmenu/template-and-style-selectors)

* [Use Commands with the RadContextMenu](https://www.telerik.com/products/wpf/documentation/knowledge-base/kb-contextmenu-use-commands)
