![](/img/trans.png)
[英]WPF – how to attach VisualStateGroups in control template created in code-behind?
[英]How to attach behavior for WPF control created in code behind?
我正在使用如何使WPF組合框具有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)
您可以使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.