Back to Devexpress

Binding to Data

wpf-6661-controls-and-libraries-navigation-controls-navigation-bar-binding-to-data.md

latest3.0 KB
Original Source

Binding to Data

  • Jul 19, 2021
  • 2 minutes to read

The DXNavBar control can obtain group and item information from a data source. For this purpose, you can use the NavBarControl.ItemsSource property - to specify the source of the data, and the NavBarControl.GroupDescription property - to specify the name of a data source field, by which the values of data source items should be grouped within the NavBarControl.

Example of Data Binding

Below is a simple example that demonstrates how a NavBarControl can be easily bound to a simple, plain data table containing two columns (“Group” and “Item”) and how the NavBarControl visualizes the table data by grouping them by the “Group” column values.

In this example, a table with the following data content is created:

GroupItem
Group 1Item 1-1
Group 1Item 1-2
Group 1Item 1-3
Group 2Item 2-1
Group 2Item 2-2
Group 2Item 2-3

Note that in the code below, the created data source object is defined as the data context for the window. Particular properties of group and item objects are bound to the required data using styles.

xaml
<Window x:Class="NavBarBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:dxn="http://schemas.devexpress.com/winfx/2008/xaml/navbar">
    <Grid>
        <dxn:NavBarControl Name="navBarControl1" ItemsSource="{Binding}" GroupDescription="Group">
            <dxn:NavBarControl.Resources>
                <Style TargetType="dxn:NavBarGroup">
                    <Setter Property="Header" Value="{Binding}"/>
                </Style>
                <Style TargetType="dxn:NavBarItem">
                    <Setter Property="Content" Value="{Binding Path=Item}"/>
                </Style>
            </dxn:NavBarControl.Resources>
        </dxn:NavBarControl>
    </Grid>
</Window>
csharp
//...
using System.Data;
using DevExpress.Xpf.NavBar;

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

            DataTable dt = new DataTable();
            dt.Columns.Add("Group", typeof(string));
            dt.Columns.Add("Item", typeof(string));
            for(int i = 1; i <= 2; i++) {
                for(int j = 1; j <= 3; j++)
                    dt.Rows.Add(new object[] { "Group " + i.ToString(), 
                        "Item " + i.ToString() + "-" + j.ToString() });
            }

            DataContext = dt;
        }
    }
}

The following image illustrates the result.