0
我正在使用How can I make a WPF combo box have the width of its widest element in XAML?如何附加在代码后面创建的WPF控件的行为?
不像的问题,我在代码中创建组合框(工具栏)的后面描述的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 *(control,bool)的方法,您可以使用它。 –
谢谢!请答复,我会接受。 –