例如,在默认情况下,某些行为附加到某种类型的所有ui元素

本文关键字:种类 类型 元素 ui 情况下 默认 例如 | 更新日期: 2023-09-27 18:02:05

例如,我想有所有的mediaelement在我的应用程序,鼠标点击mediaelement导致播放/暂停/播放/暂停…有可能说这样的行为附加到所有相关的元素在应用程序?

例如,在默认情况下,某些行为附加到某种类型的所有ui元素

可以直接遍历网格的所有子节点并适当地附加事件。

在你的XAML中一定要给你的网格一个名字:

    <Grid x:Name="gr01"...

您可以编写一个函数来附加事件,并在Window_Loaded事件中调用该函数。

namespace AttachEventDemo {
   public partial class MainWindow : Window {
      // ... usual initialization code goes here
      private void Window_Loaded( object sender, RoutedEventArgs e ) {
         AttachEvent( );
      }
      private void AttachEvent( ) {
         foreach ( var item in gr01.Children ) {
            switch ( item.GetType( ).ToString( ) ) {
               case "System.Windows.Controls.Button":
                  Button b = item as Button;
                  b.Click += b_Click;
                  txtLog.Text = "Added click event for button " + b.Name + Environment.NewLine + txtLog.Text;
                  break;
               case "System.Windows.Controls.CheckBox":
                  CheckBox cb = item as CheckBox;
                  cb.Checked += cb_Checked;
                  txtLog.Text = "Added click event for checkkbox " + cb.Name + Environment.NewLine + txtLog.Text;
                  break;
               default:
                  break;
            }
         }
      }
      void cb_Checked( object sender, RoutedEventArgs e ) {
         CheckBox cb = sender as CheckBox;
         txtLog.Text = "CheckBox " + cb.Name + " checked changed!" + Environment.NewLine + txtLog.Text;
      }
      private void b_Click( object sender, RoutedEventArgs e ) {
         Button b = sender as Button;
         txtLog.Text = "Button " + b.Name + " was clicked!" + Environment.NewLine + txtLog.Text;
      }
   }
}