实现Button的动态响应
按下不同的Button实现不同的逻辑
但用同样的代码:
1 using System.Reflection; 2 3 namespace valuableBook 4 { 5 /// <summary> 6 /// Interaction logic for Item.xaml 7 /// </summary> 8 public partial class Item : Window 9 { 10 public Item() 11 { 12 InitializeComponent(); 13 } 14 15 private void Button_Click(object sender, RoutedEventArgs e) 16 { 17 Button cmd = e.OriginalSource as Button; 18 Type type = this.GetType(); 19 Assembly assembly = type.Assembly; 20 Window win = (Window)assembly.CreateInstance(type.Namespace + "." + cmd.Tag); 21 win.ShowDialog(); 22 23 } 24 } 25 }
前台的Button
1 <StackPanel Margin="5" Button.Click="Button_Click"> 2 <Button Content="MainWindow" Tag="MainWindow"></Button> 3 </StackPanel>
Msdn上的例子:
1 using System; 2 using System.Reflection; 3 using Contoso.Libraries; 4 5 namespace Contoso.Libraries 6 { 7 public class Person 8 { 9 private string _name; 10 11 public Person() 12 { } 13 14 public Person(string name) 15 { 16 this._name = name; 17 } 18 19 public string Name 20 { get { return this._name; } 21 set { this._name = value; } } 22 23 public override string ToString() 24 { 25 return this._name; 26 } 27 } 28 } 29 30 public class Example 31 { 32 public static void Main() 33 { 34 Assembly assem = typeof(Person).Assembly; 35 Person p = (Person) assem.CreateInstance("Contoso.Libraries.Person"); 36 if (! (p == null)) { 37 p.Name = "John"; 38 Console.WriteLine("Instantiated a {0} object whose value is '{1}'", 39 p.GetType().Name, p); 40 } 41 else { 42 Console.WriteLine("Unable to instantiate a Person object."); 43 } 44 } 45 } 46 // The example displays the following output: 47 // Instantiated a Person object whose value is 'John'
作者:Ants_double
出处:https://www.cnblogs.com/ants_double/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [大拇指],谢谢!