我正在使用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">
答案 0 :(得分:2)
必须有一个名为
的方法ComboBoxWidthFromItemsBehavior.SetComboBoxWidthFromItems(control, bool)
您可以使用。