[英]In WPF how can I control whether another button clicked
我想確定在WPF中單擊了另一個按鈕。 我寫了下面的代碼,當我單擊該按鈕時,動畫起作用;然后,當我單擊相同的按鈕時,動畫起作用,就像else塊一樣。 但是我想控制是否單擊了另一個按鈕,然后我要控制else塊。
int i = 0;
private void btnDashboard_Click(object sender, RoutedEventArgs e)
{
// btnDashboard.Click += btnDashboard_Click;
// Button btnSender = (Button)sender;
if (i%2==0)
{
DoubleAnimation anim = new DoubleAnimation(250, 1470, new Duration(TimeSpan.FromMilliseconds(300)));
btnDashboard.BeginAnimation(FrameworkElement.WidthProperty, anim);
((ApplicationShell)App.Current.MainWindow).ShowPages(new UCDashboardIndicatorView());
i++;
}
else
{
DoubleAnimation anim = new DoubleAnimation(1470, 250, new Duration(TimeSpan.FromMilliseconds(300)));
btnDashboard.BeginAnimation(FrameworkElement.WidthProperty, anim);
base.OnApplyTemplate();
i++;
}
}
我該如何控制?
只需將其他Button
作為事件的訂閱者添加即可。
<Button Click="btnDashboard_Click" ... />
<Button Click="btnDashboard_Click" ... />
在事件方法中,您可以按住被單擊的按鈕:
Button btn = sender as Button;
然后,您可以將動畫應用於所需的按鈕:
btn.BeginAnimation(FrameworkElement.WidthProperty, anim);
注意:上面的代碼引用了btn
,它可以是被單擊的兩個按鈕之一 。
如果您需要通過基於被單擊的特定按鈕應用動畫來使此步驟更進一步,則可以為每個按鈕指定一個Name
並在if語句中測試btn.Name
。
如果要對兩個按鈕使用相同的Click處理程序,請嘗試以下操作:
private void btnDashboard_Click(object sender, RoutedEventArgs e)
{
Button btnSender = sender as Button;
if(btnSender.Name == "btn1")
{
//Code for Button1
}
else
{
//Code for Button2
}
}
還要確保每個按鈕在XAML中都設置了Name屬性,以便您可以在后面的代碼中對其進行訪問。 在XAML中:
<Grid>
<Button Name="btn1" Click="btnDashboard_Click"/>
<Button Name="btn2" Click="btnDashboard_Click"/>
</Grid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.