猿问

是否有类似于 RegisterClassHandler 的 DependencyProperty

我知道您可以使用EventManager该类将类处理程序注册到路由事件,以便在为该类对象触发该事件时使类的所有实例做出响应:


EventManager.RegisterClassHandler( typeof( TextBox ), Control.MouseDoubleClickEvent,

    new RoutedEventHandler( ( S, E ) => ( E.OriginalSource as TextBox )?.SelectAll( ) ) );

我正在寻找的是一种方法来做类似的事情,附加DependencyProperty到DataBinding使用该特定属性的控件类型的所有实例。


符合最小、完整和可验证示例要求...


应用程序.xaml.cs:


using System;

using System.ComponentModel;

using System.Windows;

using System.Windows.Controls;


namespace MCVE {

    /// <summary>

    /// Interaction logic for App.xaml

    /// </summary>

    public partial class App : INotifyPropertyChanged {

        public static readonly DependencyProperty FooProperty;


        public event PropertyChangedEventHandler PropertyChanged;


        static App( ) {

            EventManager.RegisterClassHandler(

                typeof( TextBox ), Control.MouseDoubleClickEvent,

                new RoutedEventHandler(

                    ( S, E ) => ( E.OriginalSource as TextBox )?.SelectAll( ) ) );

            FooProperty = DependencyProperty.RegisterAttached(

                    "Foo", typeof( string ), typeof( App) );

            //Is it possible to bind the FooProperty of all Window objects to

            //the FooSource property defined below in similar fashion 

            //to how one can call RegisterClassHandler above?

        }


        [STAThread]

        public static int Main( ) {

            App program = new App( );

            program.InitializeComponent( );

            return program.Run( );

        }


        protected override void OnStartup( StartupEventArgs e ) {

            this.FooSource = "Baz";

            base.OnStartup( e );

        }


        public static string GetFoo( Window w ) =>

            w.GetValue( FooProperty ).ToString( );

        public static void SetFoo( Window w, string value ) =>

            w.SetValue( FooProperty, value );


因此,所需的行为是,在启动程序后,之后创建的任何窗口都将通过某些数据绑定行为将FooProperty值设置为"Baz"(这样,如果FooSource属性更改,则每个窗口FooProperty属性也将更改)。


这可能吗?


神不在的星期二
浏览 192回答 1
1回答

胡子哥哥

您只需要Window.Loaded在App的构造函数中为event再添加一个事件处理程序。private App(){&nbsp; &nbsp; EventManager.ResisterClassHandler(typeof(Window), Window.LoadedEvent,&nbsp; &nbsp; &nbsp; &nbsp; (RoutedEventHandler)((s, e) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((Windows)s).SetBinding(FooProperty, new Binding("FooSource")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Source = this,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ));}而且我相信这只是一个不小心的错过,主人类型FooProperty应该是typeof(App)但不是typeof(Window)。
随时随地看视频慕课网APP
我要回答