gpt4 book ai didi

c# - WPF:在单击事件中更改动态创建的按钮的背景颜色

转载 作者:太空宇宙 更新时间:2023-11-03 21:04:55 32 4
gpt4 key购买 nike

我在点击事件上创建了一个按钮:

  private void  btnAddNewQuestion_Click(object sender, RoutedEventArgs e)
{
Button btnQuestion = new Button();
btnQuestion.Name="btn"+counter.toString();
btnQuestion.Content="Enter/Edit your question here";
btnQuestion.Background=Brushes.Grey;
btnQuestion.Click += new RoutedEventHandler(btnEnterQuestion_Click);
counter++;
}

下面是动态创建按钮的点击事件:

   private void  btnEnterQuestion_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
button.Background=Brushes.White;
}

问题:

我希望在单击按钮时,只有单击按钮的背景应更改为白色,而之前单击的按钮应将其颜色更改回灰色

为了引用,我附上了截图:

On click of first button

On click of second button

更新

我正在为 btnAddNewQuestion 添加 XAML 代码

<Button x:Name="btnAddNewQuestion" Click="btnAddNewQuestion_Click" />

最佳答案

spMain.Children 中搜索并更改所有按钮背景,然后单击下一个更改当前背景的按钮。

 private void btnEnterQuestion_Click(object sender, RoutedEventArgs e)
{
foreach (var btn in spMain.Children.OfType<Button>().Where(x=> x.Name.StartsWith("btn")))
btn.Background = Brushes.Gray;

Button button = sender as Button;
button.Background = Brushes.White;
}

关于c# - WPF:在单击事件中更改动态创建的按钮的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844632/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com