如何在 WPF 中显示复选框值和文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16817204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:53:12  来源:igfitidea点击:

How to display checkbox value and text in WPF?

c#wpfcheckboxwpf-controls

提问by mostafa hasan nezhad

I need to display value and text contained in the particular CheckBoxwhich is checked on its checked event in WPF. How to do that?

我需要显示包含CheckBox在 WPF 中检查事件的特定值中的值和文本。怎么做?

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    MessageBox.Show(........need help here......);
}

回答by Mehdi Bugnard

I'm not sure I understood your expectations. You want to retrieve the value "checked" - "unchecked" from the checkBox?

我不确定我是否理解您的期望。您想从复选框中检索值“已选中”-“未选中”?

So can you try this?

所以你可以试试这个吗?

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
     //Get the boolean current value [true or false]
     bool valueSelectedToBool = (sender as CheckBox).IsChecked;

     //Get the string current value ["true" or "false"]
     string valueSelectedToString = (sender as CheckBox).IsChecked.ToString();

     MessageBox.Show(valueSelectedToString );
} 

回答by Gauthier G. Letellier

You could try this :

你可以试试这个:

I don't know if you want the uncheck action to trigger the event but I put it.

我不知道您是否希望取消选中操作来触发事件,但我把它放在了。

In XAML :

在 XAML 中:

<CheckBox Content="CheckBox" VerticalAlignment="Top" Unchecked="CheckBox_Checked_1" Checked="CheckBox_Checked_1"/>

In C# :

在 C# 中:

  private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            CheckBox check = sender as CheckBox;
            MessageBox.Show(check.IsChecked.Value.ToString());
        }

Just tested it, it works. I hope it is what you are searching for.

刚刚测试了一下,可以用。我希望这是你正在寻找的。

回答by mostafa hasan nezhad

I'm working with WPF. I used these lines of code. In my case it works properly.

我正在使用 WPF。我使用了这些代码行。就我而言,它可以正常工作。

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    bool Chked = Convert.ToBoolean((sender as CheckBox).IsChecked);
    string ChkBoxContent = (sender as CheckBox).Content.ToString();
    TxtHabitsHx.AppendText(ChkBoxContent);
}