简体   繁体   English

仅返回复选框的值

[英]Return only the value of checked boxes

EDIT : It now works ! 编辑:现在可以使用! Thanks to Alberto's detailed explanation, I bound IsChecked to a variable, and changed the button_1_click the way he wrote it 感谢Alberto的详细说明,我将IsChecked绑定到一个变量,并更改了button_1_click他的书写方式

I'd like to return only the Content of checked boxes in a checkbox list that is defined this way in XAML : 我只想返回在XAML中以这种方式定义的复选框列表中复选框的内容:

<Grid>
    <StackPanel Width="250" Height="80"></StackPanel>
    <TextBox Name="ZoneText" Width="160" Height="20" Margin="12,215,330,76" Background="Bisque" />
    <TextBox Name="ZoneValue" Width="160" Height="20" Margin="12,239,330,52" Background="Bisque" />
    <ListBox Name="listBoxZone" ItemsSource="{Binding TheList}" Background="Azure" Margin="12,12,12,115">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Name="CheckBoxZone" Content="{Binding TheText}" Tag="{Binding TheValue}" Checked="CheckBoxZone_Checked" Margin="0,5,0,0" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Content="Validate" Height="44" HorizontalAlignment="Left" Margin="362,215,0,0" Name="button1" VerticalAlignment="Top" Width="123" Click="button1_Click" />
</Grid>

I'd like to be able to store all the content of the checked checkboxes in a list (when I press a button), but I can't seem to do it, here is what I've tried in C# : 我希望能够将选中的复选框的所有内容存储在列表中(当我按下按钮时),但是我似乎无法做到这一点,这是我在C#中尝试过的事情:

public MainWindow()
{
    InitializeComponent();
    CreateCheckBoxList();
}

public class BoolStringClass
{
    public string TheText { get; set; }
    public int TheValue { get; set; }
}

public void CreateCheckBoxList()
{
    TheList = new ObservableCollection<BoolStringClass>();

    foreach (var line in File.ReadLines(path))
    {
        if (regex1.Match(line).Success)
        TheList.Add(new BoolStringClass { TheText = "" + line, TheValue = false });
        else
        TheList.Add(new BoolStringClass { TheText = "" + line, TheValue = true });

        this.DataContext = this;
    }
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    foreach (CheckBox item in listBoxZone.Items)
    {
        List<string> selectedFOP = new List<String>();
        if (item.IsChecked == true)
        {
            selectedFOP.Add(item.Content.ToString());
        }
    }

}

But I get an error that it is impossible to do a cast of an object whose type is 'BoolStringClass' into a 'System.Windows.Controls.CheckBox' . 但我收到一个错误,无法将类型为'BoolStringClass'的对象转换为'System.Windows.Controls.CheckBox' I guess I have to use listBoxZone.ItemTemplate instead, but how can I access the checkboxes in it ? 我猜我必须改用listBoxZone.ItemTemplate ,但是如何访问其中的复选框? Thank you 谢谢

You have to change the TheValue type to a boolean 您必须将TheValue类型更改为布尔值

public class BoolStringClass
{
    public string TheText { get; set; }
    public bool? TheValue { get; set; }
}

And bind twoway the IsChecked property on the checkbox (you don't need to handle the checked changed event). 并在复选框上双向绑定IsChecked属性(您无需处理选中的更改事件)。

<CheckBox Name="CheckBoxZone" Content="{Binding TheText}" IsChecked="{Binding TheValue, Mode=TwoWay}" Margin="0,5,0,0" />

If the list can have different values when initialized you need to implement the INotifyPropertyChanged in the BoolStringClass so that checkboxes reflect the initial values (depending on your design this may not be necessary): 如果列表在初始化时可以具有不同的值,则需要在BoolStringClass中实现INotifyPropertyChanged,以便复选框反映初始值(根据您的设计,这可能不是必需的):

public class BoolStringClass : INotifyPropertyChanged
{
    private bool? _thevalue;
    public event PropertyChangedEventHandler PropertyChanged;

    public string TheText { get; set; }

    public bool? TheValue
    {
        get
        {
             return _thevalue;
        }
        set
        {
             _thevalue = value;

             OnPropertyChanged("TheValue")
        }
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

Also when creating the list in CreateCheckBoxList() use an ObservableCollection (if the number of checkboxes will not change dynamically but only on initialization here, you can use a normal list of BoolStringClass). 同样,在CreateCheckBoxList()中创建列表时,请使用ObservableCollection(如果复选框的数量不会动态变化,而仅在此处初始化时,则可以使用BoolStringClass的常规列表)。

// use global variable
ObservableCollection<BoolStringClass> TheList;

public void CreateCheckBoxList()
{
    //some code that creates a list
    TheList = new ObservableCollection<BoolStringClass>() { 
        new BoolStringClass() {TheText = "Check1", TheValue = false},
        new BoolStringClass() {TheText = "Check2", TheValue = true} 
    }
}

Then you can iterate on the list (also the copied list creation goes outside the loop!) 然后,您可以在列表上进行迭代(复制的列表创建也将超出循环范围!)

private void button1_Click(object sender, RoutedEventArgs e)
{
    List<string> selectedFOP = new List<String>();

    foreach (BoolStringClass item in TheList)
    {
        if (item.TheValue == true) selectedFOP.Add(item.ToString());
    }
}

Probably you don't need to do this copy, depending on how your program is designed. 可能不需要复制此文件,具体取决于程序的设计方式。 If you really do, you can do it in one line with LINQ (add using System.LINQ): 如果确实这样做,则可以使用LINQ(使用System.LINQ添加)在一行中完成:

private void button1_Click(object sender, RoutedEventArgs e)
{
    var selectedFOP = TheList.Where(b => b.TheValue == true).ToList();
}

I'm doing it by hand so there could be minor syntax errors. 我是手工完成的,因此可能会出现较小的语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM