如何将事件从 UserControl 传递给它的一个子控件?
How can you pass events from a UserControl to one of its children?
假设您有一个名为 ActionableListBox
的 UserControl
,它由一个 DockPanel
组成,其中包含一个 Button
和一个 ListBox
。
设置 ActionableListBox
以公开包装的 ListBox
上的属性很简单。只需在 ActionableListBox
上定义 属性 并将 getter/setter 委托给内部 ListBox
。非常直接。
但是我没有找到的是如何将 ActionableListBox
设置为 'pass thru' 事件,例如 SelectionChanged
等,以便我可以在 [=35= 中使用它].您不能 'delegate down' 像属性一样,因为事件处理程序只能出现在赋值运算符的左侧。
所以,除了被迫将其转换为完整的 CustomControl
,有什么方法可以 'pass thru' 事件,以便我可以在 [=] 中使用此 UserControl
35=]?
其实很简单。为 ActionableListBox 定义 SelectionChanged 事件。对于 ListBox
的 SelectionChanged
,在 ActionableListBox
中创建一个事件处理程序,然后触发它自己的 SelectionChanged
.
public event SelectionChangedEventHandler SelectionChanged;
...
listBox.SelectionChanged += listBox_SelectionChanged;
...
void listBox_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
SelectionChanged?.Invoke(sender, args);
}
假设您有一个名为 ActionableListBox
的 UserControl
,它由一个 DockPanel
组成,其中包含一个 Button
和一个 ListBox
。
设置 ActionableListBox
以公开包装的 ListBox
上的属性很简单。只需在 ActionableListBox
上定义 属性 并将 getter/setter 委托给内部 ListBox
。非常直接。
但是我没有找到的是如何将 ActionableListBox
设置为 'pass thru' 事件,例如 SelectionChanged
等,以便我可以在 [=35= 中使用它].您不能 'delegate down' 像属性一样,因为事件处理程序只能出现在赋值运算符的左侧。
所以,除了被迫将其转换为完整的 CustomControl
,有什么方法可以 'pass thru' 事件,以便我可以在 [=] 中使用此 UserControl
35=]?
其实很简单。为 ActionableListBox 定义 SelectionChanged 事件。对于 ListBox
的 SelectionChanged
,在 ActionableListBox
中创建一个事件处理程序,然后触发它自己的 SelectionChanged
.
public event SelectionChangedEventHandler SelectionChanged;
...
listBox.SelectionChanged += listBox_SelectionChanged;
...
void listBox_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
SelectionChanged?.Invoke(sender, args);
}