I wanted to use databinding with the ToolBarTray so I created some services and attatched properties to fullfill my needs. The final solution was this:
<ToolBarTray local:TrayBinding.ItemsSource="{Binding Path=Groups}"
local:TrayBinding.ToolBarItemsSource="Items"></ToolBarTray>
Where ItemsSource refers to the collection used to create the ToolBars and the ToolBarItemsSource refers to the property on the item bound to the ToolBar which will be used as the ItemsSource on the toolbar. Now, everything is working fine, but before I jump off and put this into production code I want to make sure that I am not doing anything stupid.
So, the logic works as follows: The TrayBinding class initializes a ToolBarTrayBinder class (this is the class which does the actual work of creating the ToolBars in the tray and keeping them in sync with the databound collection) and assigns it to the ToolBarTray which the attatched properties are defined on. Since I need to keep a mapping between each ToolBarTray and its corresponding ToolBarTrayBinder, I decided to add the ToolBarTrayBinder as a dependency property on the ToolBarTray. Below you can see the initialization logic in the TrayBindig class:
private static void InitializeBinder(ToolBarTray tray)
{
string toolsItemsSource = GetToolBarItemsSource(tray);
IEnumerable dataSource = GetItemsSource(tray);
if (string.IsNullOrEmpty(toolsItemsSource) || dataSource == null)
return;
var toolBarTrayBinder = tray.GetValue(BindingServiceProperty) as ToolBarTrayBinder;
if (toolBarTrayBinder == null)
{
toolBarTrayBinder = new ToolBarTrayBinder(tray);
tray.SetValue(BindingServiceProperty, toolBarTrayBinder);
}
toolBarTrayBinder.ItemsSource = toolsItemsSource;
toolBarTrayBinder.DataSource = dataSource;
}
And the ToolBarTrayBinder is stored in a private dependency property:
private static readonly DependencyProperty BindingServiceProperty = DependencyProperty.Register("TrayBinder",
typeof(ToolBarTrayBinder),
typeof(ToolBarTray),
new PropertyMetadata(null));
So, my question is: Is it considered a good practice to add helper classes, such as the ToolBarTrayBinder, as a dependency property on the item which the property is attached? Are there any problems, such as memory leaks or similar that can cause problems when doing this?
I don’t see a problem with this, though it’s a little bit heavy-weight for simply associating the data (you’re only associating the data and not using data binding or update notification.) There’s slightly less overhead with a simple Dictionary cache, but using a DP does give you the benefit of the DP going away if the ToolBarTray goes away (since the DependencyObject provides the storage.)