如何在列表框中为列表框C#WPF中的特定项设置复选框

时间:2016-06-06 21:21:16

标签: c# wpf checkbox listbox

我有如下列表框:

    <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="385" Margin="21,138,0,0" VerticalAlignment="Top" Width="273" ItemsSource="{Binding Path=locationList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Button Name="btnDelete" Click="btnDelete_Click" Width="15" Height="15" HorizontalAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Content="x" />
                    <CheckBox Name="checkBox" />
                    <TextBlock Name="textBox" Text="{Binding}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我想要做的是为此列表框设置特定项目的复选框。

我正在尝试这样做:

    private void button4_Click(object sender, RoutedEventArgs e)
    {
        for(int i = 0; i < listBox.Items.Count; i++)
        {
            listBox.Items[i].checkBox = false;
        }
    }

我知道我在做错误。我想将它转换为item的对象,然后将item的属性(此复选框)设置为false。愿有人纠正我吗?提前谢谢。

修改

在我尝试这样做之前:

        foreach (var item in listBox.SelectedItems)
        {
            item.
        }

但我获得的所有可能性只是标准方法:Equals,GetHashCode,GetType,ToString ......我如何引用复选框?

此外,我将提供有关洞察力的问题。我想通过文本找到一个特定项目,它在列表框(项目)中排成行,然后更改此项目的复选框(列表框中的同一行)。 要实现的第二个逻辑是将所有行设置为选中或未选中(这是我现在要做的)。

感谢您的回复。

1 个答案:

答案 0 :(得分:3)

        for (int i = 0; i < listBox.Items.Count; i++)
        {
            var item = listBox.ItemContainerGenerator.ContainerFromItem(listBox.Items[i]) as ListBoxItem;
            var template = item.ContentTemplate as DataTemplate;

            ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(item);

            CheckBox myCheckBox = (CheckBox)template.FindName("checkBox", myContentPresenter);

            myCheckBox.IsChecked = true;
        }

同样,您可以找到TextBlock(注意,您将其命名为&#34; textBox&#34; not&#34; textBlock&#34;)

            TextBlock myTextBlock = (TextBlock)template.FindName("textBox", myContentPresenter);

FindVisualChild可以在FindVisualChild reference issue

找到