【问题标题】:C# WPF Gui Checkbox Name as arrayC# WPF Gui 复选框名称为数组
【发布时间】:2019-03-10 17:56:02
【问题描述】:

我用 WPF 创建了一些 CheckBoxex。它对我的程序很重要,我可以使用数组访问我的复选框。

例如。

iGPIO[1].IsChecked

 <ScrollViewer>
            <StackPanel Margin="0,0,10,0">
                <CheckBox Name="iGPIO[0]" Content="GPIO 1"></CheckBox>
                <CheckBox Name="iGPIO[1]" Content="GPIO 2"/>
                <CheckBox Content="GPIO 3"/>
                <CheckBox Content="GPIO 4"/>
                <CheckBox Content="GPIO 5"/>
                <CheckBox Content="GPIO 6"/>
                <CheckBox Content="GPIO 7"/>
                <CheckBox Content="GPIO 8"/>
                <CheckBox Content="GPIO 9"/>
                <CheckBox Content="GPIO 10"/>
                <CheckBox Content="GPIO 11"/>
                <CheckBox Content="GPIO 12"/>
                <CheckBox Content="GPIO 13"/>
                <CheckBox Content="GPIO 14"/>
                <CheckBox Content="GPIO 15"/>
                <CheckBox Content="GPIO 16"/>
                <CheckBox Content="GPIO 17"/>
                <CheckBox Content="GPIO 18"/>
                <CheckBox Content="GPIO 19"/>
                <CheckBox Content="GPIO 20"/>
                <CheckBox Content="GPIO 21"/>
                <CheckBox Content="GPIO 22"/>
                <CheckBox Content="GPIO 23"/>
                <CheckBox Content="GPIO 24"/>
                <CheckBox Content="GPIO 25"/>
                <CheckBox Content="GPIO 26"/>
                <CheckBox Content="GPIO 27"/>
            </StackPanel>

【问题讨论】:

  • 您需要访问复选框对象本身还是仅访问复选框的值,即truefalse

标签: c# arrays wpf checkbox


【解决方案1】:

我建议使用 ListBox 对复选框和 DataTemplate 进行分组

<StackPanel>
    <ListBox Name="listBox" ItemsSource="{Binding TheList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                 <CheckBox Name="CheckBoxZone" Content="{Binding TheText}" 
                     Tag="{Binding TheValue}" Checked="CheckBoxZone_Checked"/>
            </DataTemplate> 
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

【讨论】:

    【解决方案2】:

    这是一种方法。

    首先,给您的 StackPanel 一个 Name 属性,例如“myStackPanel”。

    然后在顶部添加这个 Using,用于通过对象进行查询:

    using System.Linq;
    

    然后执行以下操作:

    // Get all available checkboxes in the StackPanel's children.
    var checkBoxes = myStackPanel.Children.OfType<CheckBox>();
    
    for (int i = 0; i < checkBoxes.Count; i++)
    {
        MessageBox.Show(checkBoxes[i].Content + ": " checkBoxes[i].IsChecked.ToString());
        // GPIO 1: true
        // GPIO 2: false
        // etc...
    }
    
    // Get first checkbox state
    MessageBox.Show(checkBoxes[0].IsChecked.ToString());
    

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 2011-08-10
      • 2015-12-21
      相关资源
      最近更新 更多