首页 > 代码库 > WPF 获取绑定的事件处理程序绑定全局资源
WPF 获取绑定的事件处理程序绑定全局资源
1. 我们想要获取绑定到 button 上面的所有 click event handler actions. 可以使用以下的代码.
namespace RoutedEventHandlerInfoTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += MainWindow_Loaded; } void MainWindow_Loaded(object sender, RoutedEventArgs e) { this.btnTest.Click+=btnTest_Click; var infos = GetRoutedEventHandlers(this.btnTest, ButtonBase.ClickEvent); } private void btnTest_Click(object sender, RoutedEventArgs e) { Console.WriteLine(" button clicked"); } /// <summary> /// Gets the list of routed event handlers subscribed to the specified routed event. /// </summary> /// <param name="element">The UI element on which the event is defined.</param> /// <param name="routedEvent">The routed event for which to retrieve the event handlers.</param> /// <returns>The list of subscribed routed event handlers.</returns> public static RoutedEventHandlerInfo[] GetRoutedEventHandlers(UIElement element, RoutedEvent routedEvent) { // Get the EventHandlersStore instance which holds event handlers for the specified element. // The EventHandlersStore class is declared as internal. var eventHandlersStoreProperty = typeof(UIElement).GetProperty( "EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic); object eventHandlersStore = eventHandlersStoreProperty.GetValue(element, null); // Invoke the GetRoutedEventHandlers method on the EventHandlersStore instance // for getting an array of the subscribed event handlers. var getRoutedEventHandlers = eventHandlersStore.GetType().GetMethod( "GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var routedEventHandlers = (RoutedEventHandlerInfo[])getRoutedEventHandlers.Invoke( eventHandlersStore, new object[] { routedEvent }); return routedEventHandlers; } } }分析下代码: 关键在 GetRoutedEventHandlers(UIElement, RoutedEvent) 方法. 这个方法首先从 UIElement 中获取一个名叫 EventHandlersStore 的私有实例属性. 通过 GetValue() 方法获取这个属性的值. 然后获取 EventHandlersStore 类的一个方法叫做 GetRoutedEventHandlers. 执行这个方法来获取 eventHandlersStore 实例中的类型为 routedEvent 的handlers.
2. 如果有一个全局的资源, 例如一个List<string> 我们想要绑定到前台界面一个下拉框中. 做法如下:
首先把这个资源放到 Application Resource 中.
System.Windows.Application.Current.Resources.Add("AllFlows", Launcher.AllFlows);然后, 在 xaml 文件中将这个资源用 DynamicResource 绑定到控件上.
<MultiSelectComboBox x:Name="cboIgnoreFlows" ItemsSource="{DynamicResource AllFlows}" SelectedValue=http://www.mamicode.com/"{Binding SelectedIgnoreFlows, Mode=TwoWay}">
WPF 获取绑定的事件处理程序绑定全局资源
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。