Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles CA and Austin TX. Follow galratner on Twitter Google
Bind a generic dictionary to a RibbonDropDownButton in a WPF Ribbon Control

RibbonDropDownButton can show a list of items inside a Ribbon button. You can hard code the items by adding a collection of menu items like so:

<r:RibbonDropDownButton Command="me:AppCommands.OtherReports">

<MenuItem Header="Cash Flow Report" />

      <MenuItem Header="Favorites Report" />

      <MenuItem Header="Spending Report" />

      <MenuItem Header="Savings Report" />

      <MenuItem Header="Credit Report" />

</r:RibbonDropDownButton>

 You can also bind the items to a data source. Let's bind the RibbonDropDownButton to a generic dictionary. First lets compose the dictionary:

Dictionary<int, string> myData = new Dictionary<int, string>();

myData.Add(1, "my string");

Next, lets bind the ItemsSource like so:

MyRibbonDropDownButton.ItemsSource = myData; 

Now that our RibbonDropDownButton’s items collection contain our dictionary, lets make sure it displayes the data correctly by adding an ItemTemplate

<r:RibbonDropDownButton Name="MyRibbonDropDownButton" Command="{StaticResource PingGroupCommand}" MenuItem.Click="RibbonDropDownButton_Click">

<r:RibbonDropDownButton.ItemTemplate>

            <DataTemplate>

                  <StackPanel>

                        <TextBlock Text="{Binding Value}" />

                  </StackPanel>

            </DataTemplate>

      </r:RibbonDropDownButton.ItemTemplate>

</r:RibbonDropDownButton>

Notice we have used {Binding Value} in order to bind the TextBlock to the Value of our dictionary. We could also use the {Binding Key} if we need to show the key.
Now that we are showing the items correctly, we can track user selection using the MenuItem.Click event. A MenuItem is actually a HeaderedItemsControl so we are going to have to base type cast it in order to get the item’s key

private void RibbonDropDownButton_Click(object sender, RoutedEventArgs e)

        {

            int myKey = ((System.Collections.Generic.KeyValuePair<int, string>)(((System.Windows.Controls.HeaderedItemsControl)(e.OriginalSource)).Header)).Key;

         }

The end result will be a RibbonDropDownButton that can be populated from a database, XML file or any other data source.


Posted 28 Jan 2010 6:31 AM by Gal Ratner
Filed under: ,

Powered by Community Server (Non-Commercial Edition), by Telligent Systems