Search code examples
c#wpfattachedbehaviors

How to attach behavior for WPF control created in code behind?


I am using behavior for ComboBox described in How can I make a WPF combo box have the width of its widest element in XAML?

unlike in question I'm creating ComboBox (for toolbar) in code behind:

    private static ComboBox GetCombobox(ToolbarItemViewModel item)
    {
        var cmbBox = new ComboBox();
        cmbBox.Name = item.Name;
        item.CmbBoxItems = new ObservableCollection<KeyValuePair<string, string>>(NisDllInterface.GetComboBoxValues(NisDllInterface.MainFrameName, item.Name));
        Binding itemsBinding = new Binding("CmbBoxItems");
        itemsBinding.Source = item;
        cmbBox.SetBinding(ComboBox.ItemsSourceProperty, itemsBinding);
        cmbBox.DisplayMemberPath = "Value";

        Binding selItemBinding = new Binding("SelectedItem");
        selItemBinding.Source = item;
        cmbBox.SetBinding(ComboBox.SelectedItemProperty, selItemBinding);

        return cmbBox;
    }

I get the example somewhat working by adding Loaded event handler in method above:

        cmbBox.Loaded += (sender, args) =>
        {
            ComboBox comboBox = sender as ComboBox;
            Action action = () => { comboBox.SetWidthFromItems(); };
            comboBox.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
        };

However I would like to know how can I attach behavior in code behind in same way it's done in XAML:

<ComboBox behaviors:ComboBoxWidthFromItemsBehavior.ComboBoxWidthFromItems="True">

Solution

  • There must be a method called something like

    ComboBoxWidthFromItemsBehavior.SetComboBoxWidthFromItems(c‌​ontrol, bool) 
    

    which you may use.