如何在WPF中引发代码隐藏中按钮的单击事件
我正在处理WPF应用程序,我想引发我在运行时早期为按钮创建的按钮的点击事件。我想按钮点击应该是动态的 例如:我有两个按钮,一个是City1,一个是State1,两个都有Click事件,我有另一个按钮,名称相同City2和State2。我想要的是我想要引发城市1点击事件和州1点击事件 这是我的密码:如何在WPF中引发代码隐藏中按钮的单击事件,wpf,xaml,Wpf,Xaml,我正在处理WPF应用程序,我想引发我在运行时早期为按钮创建的按钮的点击事件。我想按钮点击应该是动态的 例如:我有两个按钮,一个是City1,一个是State1,两个都有Click事件,我有另一个按钮,名称相同City2和State2。我想要的是我想要引发城市1点击事件和州1点击事件 这是我的密码: Button getSpecificButton = XYZ.Common.ExtensionMethods.FindLogicalChildren<Button>(this).Where
Button getSpecificButton = XYZ.Common.ExtensionMethods.FindLogicalChildren<Button>(this).Where(btn1 => btn1.Content == Intrbt.Content).FirstOrDefault();
if (getSpecificButton != null && getSpecificButton.Content != null)
{
//getSpecificButton.Name = getSpecificButton.Content.ToString();
//getSpecificButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
}
Button getSpecificButton=XYZ.Common.ExtensionMethods.FindLogicalChildren(this).Where(btn1=>btn1.Content==Intrbt.Content).FirstOrDefault();
if(getSpecificButton!=null&&getSpecificButton.Content!=null)
{
//getSpecificButton.Name=getSpecificButton.Content.ToString();
//getSpecificButton.RaiseEvent(新路由EventArgs(ButtonBase.ClickEvent));
}
我有一个扩展方法,用来获取应用程序中的所有按钮,我得到了一个异常
public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
foreach (object rawChild in LogicalTreeHelper.GetChildren(depObj))
{
if (rawChild is DependencyObject)
{
DependencyObject child = (DependencyObject)rawChild;
if (child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindLogicalChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
}
公共静态IEnumerable FindLogicalChildren(DependencyObject depObj),其中T:DependencyObject
{
if(depObj!=null)
{
foreach(LogicalTreeHelper.GetChildren(depObj)中的对象rawChild)
{
if(rawChild是DependencyObject)
{
DependencyObject子对象=(DependencyObject)rawChild;
如果(孩子是T)
{
收益率(T)子项;
}
foreach(T childOfChild in findlogical child(child))
{
儿童收益率;
}
}
}
}
}
但此代码不起作用,请尝试解决此问题
getSpecificButton.Click += btn_Click;
//separate method
private void btn_Click(object sender, RoutedEventArgs e)
{
// ...
}
这会奏效的。
但是请使用Adwaenyth评论的ICommand。我建议使用
ICommand
实现来绑定按钮.命令
属性。然后,您不需要遍历可视化树并模拟单击按钮,只需在代码隐藏中执行ICommand
,甚至不需要访问可视化树。我不能使用ICommand,因为有100个按钮我必须更改完整的代码。所以请提供一个解决方案state1.RaiseEvent(newroutedeventargs(ButtonBase.ClickEvent));在编写按钮的特定名称时,其工作正常。但是如果我将一个按钮分配为getSpecificButton.RaiseEvent(newRoutedEventArgs(ButtonBase.ClickEvent));正在引发异常。什么异常?NullReferenceException?:)WindowsBase.dll中发生“System.StackOverflowException”类型的未处理异常。这实际上对我不起作用。因为我不知道在运行时单击按钮,所以无论按钮是什么,都应该调用相关的提升单击事件。例如,如果点击状态,则点击状态应升高,如果点击城市,则点击城市应升高,但采用相同的方法,我可以通过If else或switch实现这一点,但我有100个按钮,我希望避免100个切换或If block,这就是我问的原因