【发布时间】:2017-08-16 22:21:20
【问题描述】:
我正在使用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*(control, bool) 的方法,您可以使用它。
-
谢谢!请回答,我会接受的。
标签: c# wpf attachedbehaviors