我有一个包含 ListBox 的用户控件。
我想在包装 listBox.SelectionChanged 事件的用户控件上公开一个 SelectionChanged 事件。
这样,当列表框项目选择发生变化时,我自己在用户控件上的自定义事件也会在那之后被触发......
我该怎么做?任何样品将不胜感激。谢谢!
我有一个包含 ListBox 的用户控件。
我想在包装 listBox.SelectionChanged 事件的用户控件上公开一个 SelectionChanged 事件。
这样,当列表框项目选择发生变化时,我自己在用户控件上的自定义事件也会在那之后被触发......
我该怎么做?任何样品将不胜感激。谢谢!
如果您希望 UserControl 上的自定义事件冒泡可视化树,则应将其公开为RoutedEvent。在 .xaml.cs 文件中,您需要将事件注册为路由事件,然后实现自定义处理程序和事件 args 类。
XAML:
<UserControl x:Class="WpfApplication1.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<ListView Name="myListView" SelectionChanged="OnSelectionChanged_"/>
</Grid>
</UserControl>
代码:
public partial class MyUserControl : UserControl
{
public delegate void CustomSelectionChangedEventHandler(object sender, SelectionChangedRoutedEventArgs args);
public static readonly RoutedEvent CustomSelectionChangedEvent = EventManager.RegisterRoutedEvent(
"CustomSelectionChanged", RoutingStrategy.Bubble, typeof(CustomSelectionChangedEventHandler), typeof(MyUserControl));
public event RoutedEventHandler CustomSelectionChanged
{
add { AddHandler(CustomSelectionChangedEvent, value); }
remove { RemoveHandler(CustomSelectionChangedEvent, value); }
}
public MyUserControl()
{
InitializeComponent();
}
private void OnSelectionChanged_(object sender, SelectionChangedEventArgs e)
{
RaiseEvent(new SelectionChangedRoutedEventArgs(myListView, CustomSelectionChangedEvent, e.AddedItems, e.RemovedItems));
}
}
public class SelectionChangedRoutedEventArgs : RoutedEventArgs
{
public IList AddedItems { get; set; }
public IList RemovedItems { get; set; }
public SelectionChangedRoutedEventArgs(object source, RoutedEvent routedEvent, IList addedItems, IList removedItems)
: base(routedEvent, source)
{
AddedItems = addedItems;
RemovedItems = removedItems;
}
}
然后,您的控件的调用者将为 CustomSelectionChanged 事件提供一个事件处理程序,其签名为:
private void OnCustomSelectionChanged(object sender, SelectionChangedRoutedEventArgs e) { }
我不确定包装是最好的方法,即使你可以包装它。我建议只定义您自己的事件,并在与 listBox.SelectionChanged 挂钩的处理程序中触发您自己的事件。然后,您可以将原始列表框事件中的任何数据传递给您自己的事件。
添加示例:
public partial class MainWindow : Window
{
public delegate void CustomSelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);
public event CustomSelectionChangedEventHandler CustomSelectionChanged;
public MainWindow()
{
InitializeComponent();
listBox1.SelectionChanged += delegate(object sender, SelectionChangedEventArgs e)
{
OnCustomSelectionChanged(e);
};
}
void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
OnCustomSelectionChanged(e);
}
//We'll use the system defined SelectionChangedEventArgs type instead of creating a derived EventArgs class
protected virtual void OnCustomSelectionChanged(SelectionChangedEventArgs e)
{
if (CustomSelectionChanged != null)
CustomSelectionChanged(this, e);
}
}
进一步阅读: