【问题标题】:WPF:change background color of dynamically created buttons on a single click eventWPF:在单击事件上更改动态创建的按钮的背景颜色
【发布时间】:2017-01-25 06:11:25
【问题描述】:

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

  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;
        }

问题:

我希望在单击按钮时,仅单击按钮的背景应更改为 White,而之前单击的按钮应将其颜色更改回 Grey

我附上截图供参考:

On click of first button

On click of second button

更新

我正在为 btnAddNewQuestion 添加 XAML 代码

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

【问题讨论】:

  • 听起来你想要一个单选按钮组(零个或一个选中)的功能,每个单选按钮都有自定义的视觉表示。欢迎使用 WPF,这是可能的,您不需要太多代码。

标签: c# wpf xaml button


【解决方案1】:

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;
    }

【讨论】:

    【解决方案2】:

    这是我让它工作的代码,刚刚创建了一个新项目并尝试在设计视图上制作 1 个按钮,然后以编程方式创建另一个按钮并将其设置在堆栈面板中。单击第二个按钮时,在单击事件中,您按名称调用第一个按钮并更改其背景...希望这就是您所需要的。

    代码隐藏

    int counter = 0;
        private void btnAddNewQuestion_Click(object sender, RoutedEventArgs e)
        {
            Button btnQuestion = new Button();
            btnQuestion.Name = "btn" + counter.ToString();
            spMain.Children.Add(btnQuestion);
            btnQuestion.Content = "Enter/Edit your question here";
            btnQuestion.Background = Brushes.Gray;
            btnQuestion.Click += new RoutedEventHandler(btnEnterQuestion_Click);
            counter++;
        }
    
        private void btnEnterQuestion_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.Background = Brushes.White;
            button1.Background = Brushes.Gray; // change of first buttons color
        }
    

    XAML

     <Grid>
        <StackPanel x:Name="spMain">
            <Button x:Name="button1" Content="Button" Click="btnAddNewQuestion_Click"/>
        </StackPanel>
    </Grid>
    

    【讨论】:

    • @Tushar,那么您做错了:P 我注意到您刚刚添加了定义事件的 xaml 代码,这是一个好的开始,请确保您的事件被定义为私有无效,就像我的回答一样,从您的图片中,我假设您拥有所有正确的 xaml 代码,您能否更新您的问题并发布您的所有代码
    【解决方案3】:

    我想向您展示一种更侧重于 XAML 的方法,其中按钮在视图中以 RadioButton 的形式进行管理,在后面的代码中以 QuestionButtonViewModel 形式进行管理。颜色的变化由ControlTemplate.Triggers 基于IsChecked 属性管理。

    XAML:

    <Grid x:Name="grid1">
        <Grid.Resources>
            <ControlTemplate x:Key="QuestionButtonControlTemplate" TargetType="{x:Type RadioButton}">
                <Border x:Name="buttonBorder" BorderBrush="DarkGray" Background="WhiteSmoke" BorderThickness="1" Padding="5">
                    <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Left"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="buttonBorder" Property="BorderBrush" Value="Goldenrod"/>
                        <Setter TargetName="buttonBorder" Property="Background" Value="White"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Grid.Resources>
    
        <StackPanel Width="300" Margin="5">
            <ItemsControl ItemsSource="{Binding QuestionButtons}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <RadioButton
                            Content="{Binding QuestionText}"
                            Click="RadioButton_Click"
                            Margin="3"
                            GroupName="QuestionButtons"
                            Template="{StaticResource QuestionButtonControlTemplate}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
    
            <Button Content="Add new Question" Click="AddQuestion_Click" Margin="3"/>
        </StackPanel>
    </Grid>
    

    代码背后:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            QuestionButtons = new ObservableCollection<QuestionButtonViewModel>();
    
            Loaded += MainWindow_Loaded;
        }
    
        public ObservableCollection<QuestionButtonViewModel> QuestionButtons { get; set; }
    
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            grid1.DataContext = this;
        }
    
        private void AddQuestion_Click(object sender, RoutedEventArgs e)
        {
            QuestionButtons.Add(new QuestionButtonViewModel() { QuestionText = "Enter/Edit your question here" });
        }
    
        private void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            // whatever you want to do, other than setting visual things
        }
    
    }
    
    public abstract class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChangedEvent([CallerMemberName]string prop = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
        }
    }
    
    public class QuestionButtonViewModel : BaseViewModel
    {
        private string _QuestionText;
        public string QuestionText
        {
            get { return _QuestionText; }
            set
            {
                if (_QuestionText != value)
                {
                    _QuestionText = value;
                    RaisePropertyChangedEvent();
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2014-10-10
      • 2014-10-09
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多