我知道您可以使用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屬性也將更改)。這可能嗎?
1 回答

胡子哥哥
TA貢獻1825條經驗 獲得超6個贊
您只需要Window.Loaded在App的構造函數中為event再添加一個事件處理程序。
private App()
{
EventManager.ResisterClassHandler(typeof(Window), Window.LoadedEvent,
(RoutedEventHandler)((s, e) =>
((Windows)s).SetBinding(FooProperty, new Binding("FooSource")
{
Source = this,
}
));
}
而且我相信這只是一個不小心的錯過,主人類型FooProperty應該是typeof(App)但不是typeof(Window)。
- 1 回答
- 0 關注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消