简体   繁体   中英

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">

There must be a method called something like

ComboBoxWidthFromItemsBehavior.SetComboBoxWidthFromItems(c‌​ontrol, bool) 

which you may use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM