我正在WPF應用程序上工作,我想提高我在運行時爲按鈕創建的按鈕的點擊事件。我想按鈕點擊應該是動態的 例如:我有兩個按鈕一個是City1,一個是State1,兩個都有Click事件,我有另一個同名的City2和State2的Button。我想是我想提出City1點擊的事件和以及狀態1點擊 這裏是我的代碼:如何提高WPF中後臺代碼中按鈕的點擊事件
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));
}
我有用於獲得應用程序的所有按鈕,我在這裏流汗外,這個擴展方法。
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;
}
}
}
}
}
但此代碼不工作請嘗試解決此問題。
我會建議使用'ICommand'實現來綁定一個'Button.Command'屬性。然後,您不需要遍歷可視化樹並模擬點擊按鈕,而只需在後面的代碼中執行'ICommand',而無需訪問可視化樹。 – Adwaenyth
我無法使用ICommand因爲有100個按鈕,我必須更改完整的代碼。所以請提供一個解決方案 –
State1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));雖然寫一個特定的名稱的按鈕,它的工作正常。但如果我assiging按鈕作爲getSpecificButton.RaiseEvent(新RoutedEventArgs(ButtonBase.ClickEvent));拋出異常。 –