某些行为如何附加到默认情况下某些类型的所有ui元素?

时间:2013-03-02 13:22:29

标签: c# .net xaml

例如,我想在我的应用程序中使用所有MediaElements,在鼠标点击mediaelement后导致播放/暂停/播放/暂停...可以说这样的行为可以附加到app中的所有相关元素吗?

1 个答案:

答案 0 :(得分: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;
      }
   }
}