0

例如,我希望我的应用程序中的所有 MediaElements 在鼠标单击 mediaelement 后会导致播放/暂停/播放/暂停...可以说这种行为附加到应用程序中的所有关联元素吗?

4

1 回答 1

0

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

在您的 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;
      }
   }
}
于 2013-03-02T16:53:20.113 回答