如何为在代码隐藏中创建的 WPF 控件附加行为?

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

我正在使用 How can I make a WPF combo box have the width of its widest element in XAML?

中描述的 ComboBox 行为

与问题不同,我在后面的代码中创建 ComboBox(用于工具栏):

    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;
    }

通过在上面的方法中添加 Loaded 事件处理程序,我使该示例有些工作:

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

但是我想知道如何以与 XAML:

相同的方式在代码后面附加行为
<ComboBox behaviors:ComboBoxWidthFromItemsBehavior.ComboBoxWidthFromItems="True">

必须有一个名为

的方法
ComboBoxWidthFromItemsBehavior.SetComboBoxWidthFromItems(c‌​ontrol, bool) 

你可能会用到。