Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF:更改单击事件中动态创建的按钮的背景色_C#_Wpf_Xaml_Button - Fatal编程技术网

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

C# WPF:更改单击事件中动态创建的按钮的背景色,c#,wpf,xaml,button,C#,Wpf,Xaml,Button,我在单击事件上创建了一个按钮: private void btnAddNewQuestion_Click(object sender, RoutedEventArgs e) { Button btnQuestion = new Button(); btnQuestion.Name="btn"+counter.toString(); btnQuestion.Content="Enter/Edit your question

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

  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;
        }
问题:

我想在按钮点击时,只有点击按钮的背景应该变为白色,而之前点击的按钮应该变回灰色

作为参考,我附上一个屏幕截图:

更新

我正在为btnAddNewQuestion添加XAML代码


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

代码隐藏

XAML


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

代码隐藏

XAML

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

我想向您展示一种更加注重XAML的方法,其中按钮在视图中作为RadioButton管理,在代码隐藏中作为QuestionButtonViewModel管理。颜色的更改由基于IsChecked属性的ControlTemplate.Triggers管理

XAML:

代码隐藏:

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

我想向您展示一种更加注重XAML的方法,其中按钮在视图中作为RadioButton管理,在代码隐藏中作为QuestionButtonViewModel管理。颜色的更改由基于IsChecked属性的ControlTemplate.Triggers管理

XAML:

代码隐藏:

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

@Tushar,那么你做错了什么:P我注意到你刚刚添加了xaml代码,它定义了事件,这是一个好的开始,确保你的事件定义为私有的void,就像我的回答一样,从你的图片中我假设你有所有正确的xaml代码,你能更新你的问题并发布你所有的问题吗code@Tushar,然后你做错了什么:P我注意到你刚刚添加了xaml代码,它定义了事件,这是一个好的开始,确保你的事件定义为private void,就像我的回答一样,从你的图片中我假设你拥有所有正确的xaml代码,你能更新你的问题并发布你所有的代码吗听起来像你想要一个单选按钮组的功能,或者一个选择了每个单选按钮的自定义视觉表示。欢迎使用WPF,这是可能的,您不需要太多的代码。听起来您希望单选按钮组的功能为零,或者选择一个具有自定义单选按钮视觉表示的组。欢迎使用WPF,这是可能的,您不需要太多代码。
<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();
            }
        }
    }
}