Как мне получить доступ к имени CheckBox внутри ListBox? - PullRequest
0 голосов
/ 03 мая 2019

Невозможно получить доступ к этим отчетам CheckBox в моем коде C #.

Я могу получить доступ к списку списков отчетов в моем коде, но не к отчетам.

<ListBox x:Name="reportsListBox" Grid.Row="0"
                         Background="Transparent" BorderBrush="Transparent" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                         ItemTemplate="{Binding DynamicReportsList}" Visibility="Visible"  Foreground="WhiteSmoke" Grid.RowSpan="2" Margin="156,0,2,0" Grid.ColumnSpan="2" 
                         SelectionMode="Multiple">
                    <ListBox.Resources>
                        <Style TargetType="ListBoxItem">
                            <Setter Property="OverridesDefaultStyle" Value="True"/>
                            <Setter Property="SnapsToDevicePixels" Value="True"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="ListBoxItem">
                                        <CheckBox x:Name="reportsCheckBox" Margin="5,2" Style="{StaticResource CheckboxStyle}"
                                              IsChecked="{Binding ElementName=DailyReports, Path=IsCheckedBoxChecked}"
                                              Foreground="WhiteSmoke"
                                              FontSize="14">
                                            <ContentPresenter />
                                        </CheckBox>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </ListBox.Resources>
                </ListBox>

Итак, я хочу получить доступ к своему флажку следующим образом:

private void btnCancel_Event(object sender, EventArgs e)
{
    foreach (CheckBox c in reportsCheckBox)
    {
         c.isChecked = false;
    }
}

Ответы [ 2 ]

0 голосов
/ 04 мая 2019

Итак, первый ответ из этой статьи фактически решил мою проблему. https://social.msdn.microsoft.com/Forums/vstudio/en-US/81e92a50-d0a2-4e70-93ab-e7b374858087/how-to-get-the-check-boxes-which-are-dynamically-created-in-xaml?forum=wpf

Также вместо cb.IsEnabled = false; Я сделал cb.IsChecked = false; Кроме того, у меня есть настройки привязки из комментария AmRo . Так что с привязками, установленными на месте, и с помощью этой статьи - это решило мою проблему.

XAML код:

<ListBox x:Name="reportsListBox" Grid.Row="0"
                         Background="Transparent" BorderBrush="Transparent" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                         ItemTemplate="{Binding DynamicReportsList}" Visibility="Visible"  Foreground="WhiteSmoke" Grid.RowSpan="2" Margin="4,0,0,0" 
                         SelectionMode="Multiple" Grid.Column="1">
                    <ListBox.Resources>
                        <Style TargetType="ListBoxItem">
                            <Setter Property="OverridesDefaultStyle" Value="True"/>
                            <Setter Property="SnapsToDevicePixels" Value="True"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="ListBoxItem">
                                        <CheckBox Name="reportsCheckBox" IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"
                                                  Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"
                                                  Style="{StaticResource CheckboxStyle}" Foreground="WhiteSmoke" FontSize="20" IsEnabled="{Binding enabled}"/>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </ListBox.Resources>
                </ListBox>

C # Код:

private void btnCancel_Event(object sender, EventArgs e)
{
    foreach (var item in reportsListBox.Items)
    {
        ListBoxItem lbi = reportsListBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
                    CheckBox cb = FindVisualChild<CheckBox>(lbi);
                    if (cb != null)
                        cb.IsChecked = false;
    }
}
0 голосов
/ 04 мая 2019

Попробуйте:

[ОБНОВЛЕНО]

Вместо добавления строковых значений непосредственно используйте ListBoxItem , например:

reportsListBox.Items.Add("Item1"); // thrown exception
reportsListBox.Items.Add("Item2"); // thrown exception
reportsListBox.Items.Add("Item3"); // thrown exception

reportsListBox.Items.Add(new ListBoxItem {Content = "Item1" });
reportsListBox.Items.Add(new ListBoxItem {Content = "Item2" });
reportsListBox.Items.Add(new ListBoxItem {Content = "Item3" });

XAML:

<ListBox x:Name="reportsListBox" 
         Grid.Row="0"
         Background="Transparent" BorderBrush="Transparent" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
         ItemTemplate="{Binding DynamicReportsList}" Visibility="Visible"  Foreground="WhiteSmoke" Grid.RowSpan="2" Margin="156,0,2,0" Grid.ColumnSpan="2" 
         SelectionMode="Multiple">
    <ListBox.Resources>
        <Style TargetType="ListBoxItem">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">

                        <CheckBox IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"  
                                  Content="{Binding Path=Content,    RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"/>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Resources>

    <!-- This is my sample items -->
    <ListBoxItem Content="Item 1"/>
    <ListBoxItem Content="Item 2"/>
    <ListBoxItem Content="Item 3"/>
    <ListBoxItem Content="Item 4"/>
</ListBox>

C #:

private void btnCancel_Event(object sender, EventArgs e)
{
       var items =  reportsListBox.Items;

       foreach (var item in items)
       {
          if (item is ListBoxItem)
             ((ListBoxItem)item).IsSelected = false;
       }
}

Выход:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...