Click here to Skip to main content
16,015,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am Working on a Backuptool but now i ran into a problem, all my Items in my ListBox where they were read from an OpenFolderDialog all have checkboxes. Now here is my Problem, I want to get the checked Items into another ListBox called lbSelectedItems from where they should get packed into a rar file after i chose all files i wanna save.

But how can i get the checked Items into my second Listbox and how can they keep the names?

Thats my Code:

public partial class MainWindow : Window
    {
        //DispatcherTimer timer = new DispatcherTimer();

        private DispatcherTimer timer;

        public string ParentPath;
        public int RepeatNum = 0;
        public int StartLoop = 0;
        public bool TimerActive = false;


        public MainViewModel Model
        {
            get => this.DataContext as MainViewModel;
            set => this.DataContext = value;
        }


        public MainWindow()
        {
            InitializeComponent();

            ReloadPath();



            FolderBrowserDialog dialog = new FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();
            dialog.Dispose();
            string selectedPath = dialog.SelectedPath;
            Model.TryNavigateToPath(selectedPath);
            tbCurrentPath.Text = selectedPath;


            if (tbCurrentPath.Text != null)
            {
                StartLoop = 1;
            }



            //timer.Interval = TimeSpan.FromMilliseconds(200);
            //timer.Tick += Timer_Tick;
        }

        private void LoadDirectory(string path)
        {

            if (StartLoop == 1)
            {
                while (RepeatNum <= 200)
                {
                    Thread.Sleep(500);
                    if (tbCurrentPath.Text != null)
                    {
                        LoadCurrentPath();
                        RepeatNum++;
                    }

                }
            }

        }

        public void LoadCurrentPath()
        {
            tbCurrentPath.Text = Model.CurrentPath;
        }

        private void btnDirUp_Click(object sender, RoutedEventArgs e)
        {
            LoadCurrentPath();
            //FillProgressBar();
        }



        List<object> Paths = new List<object>();


        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (LbData.SelectedItem != null)
            {
                // Extrahieren des ausgewählten Elements
                string selectedItem = LbData.SelectedItem.ToString();

                // Hinzufügen des Elements zur lbSelectedItems-ListBox
                lbSelectedItems.Items.Add(selectedItem);

                lbSelectedItems.ItemsSource = selectedItem;
            }

            lbSelectedItems.Items.Add(LbData.SelectedItems);
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {

            lbSelectedItems.Items.Remove(LbData.SelectedItems);
        }

        private void tbCurrentPath_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
        }

        //private void FillProgressBar()
        //{
        //    pgTesting.Maximum = 100;
        //    while (pgTesting.Value != 100)
        //    {
        //        pgTesting.Value++;
        //        Thread.Sleep(200);
        //    }
        //}

        private void Timeout()
        {
            btnTestReaction.Visibility = Visibility.Hidden;
            Thread.Sleep(500);

            btnTestReaction.Visibility = Visibility.Visible;
        }

        private void ReloadPath()
        {
            Thread.Sleep(100);

            ListBoxItem selectedItem = LbData.SelectedItem as ListBoxItem;
            if (selectedItem != null)
            {
                string selectedPath = selectedItem.Content.ToString();
                // Verarbeiten Sie den ausgewählten Pfad hier
            }
        }

        private void LbData_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            foreach (object item in e.AddedItems)
            {
                // Item wurde ausgewählt
            }

            foreach (object item in e.RemovedItems)
            {
                // Item wurde abgewählt
            }

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ReloadPath();

        }

        private void LbData_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void LbData_SourceUpdated(object sender, DataTransferEventArgs e)
        {
        }


        //private void Timer_Tick(object sender, EventArgs e)
        //{
        //    // Hier den Code zum Aktualisieren der ProgressBar einfügen
        //    if (pgTesting.Value < pgTesting.Maximum)
        //    {
        //        pgTesting.Value += 1;
        //    }
        //    else
        //    {
        //        // ProgressBar hat den Maximalwert erreicht, Timer stoppen
        //        timer.Stop();
        //    }
        //}

        //private void btnTestReaction_Click(object sender, RoutedEventArgs e)
        //{
        //    TimerActive = true;
        //}


        private void btnTestReaction_Click(object sender, RoutedEventArgs e)
        {
            // Set up the timer to call the Tick event every 200 milliseconds
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(50);
            timer.Tick += timer_Tick;

            // Start the timer
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            // Increase the value of the progress bar by 1
            pgTesting.Value +=0.75;

            // Check if the progress bar is full
            if (pgTesting.Value == pgTesting.Maximum)
            {
                // Stop the timer
                timer.Stop();

                // Reset the progress bar
                pgTesting.Value = 0;

                // Display a message
                System.Windows.MessageBox.Show("Test complete!");
            }
        }

    }
}




XAML:

<Window x:Class="FileExplorer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FileExplorer" 
        xmlns:viewmodels="clr-namespace:FileExplorer.ViewModels"
        mc:Ignorable="d"
        Title="PT_BackupTool" 
        Icon="favicon.ico"
        Height="720" Width="1280"
        Style="{DynamicResource CustomWindowStyle}" Loaded="Window_Loaded">
    <Window.DataContext>
        <viewmodels:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid VerticalAlignment="Top" Height="20" Margin="-1,27,447,0">
            <TextBlock Text="Ico" VerticalAlignment="Center" Margin="5,2,0,2" HorizontalAlignment="Left" Width="20"/>
            <TextBlock Text="File Name" VerticalAlignment="Center" Margin="29,2,410,2"/>
            <TextBlock Text="Date Created" VerticalAlignment="Center" Margin="0,2,283,2" HorizontalAlignment="Right" Width="125" TextAlignment="Center"/>
            <TextBlock Text="Date last Modified" VerticalAlignment="Center" Margin="0,2,156,2" HorizontalAlignment="Right" Width="125" TextAlignment="Center"/>
            <TextBlock Text="Type" VerticalAlignment="Center" Margin="0,2,84,2" HorizontalAlignment="Right" Width="70" TextAlignment="Center"/>
            <TextBlock Text="Size" VerticalAlignment="Center" Margin="0,2,7,2" HorizontalAlignment="Right" Width="75" TextAlignment="Center"/>
        </Grid>
        <ListBox x:Name="LbData" ItemsSource="{Binding FileItems, UpdateSourceTrigger=PropertyChanged}"
                 HorizontalContentAlignment="Stretch" Margin="0,47,0,0" HorizontalAlignment="Left" Width="824" SelectionChanged="LbData_SelectionChanged" SourceUpdated="LbData_SourceUpdated" >
            <ListBox.Resources>
                <Style TargetType="ListBoxItem">
                    <Setter Property="OverridesDefaultStyle" Value="true" />
                    <Setter Property="SnapsToDevicePixels" Value="true" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListBoxItem">
                                <CheckBox Margin="5,2"
                                          IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked">
                                    <ContentPresenter />
                                </CheckBox>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.Resources>
        </ListBox>


        <Grid>
            <Frame x:Name="FrameDatas" Margin="829,46,0,0" BorderBrush="#FF3C3C3C" BorderThickness="1">
            </Frame>
            <Button x:Name="btnBack" Content=" ← " HorizontalAlignment="Left" Margin="10,5,0,0" VerticalAlignment="Top" Width="20"></Button>
            <Button x:Name="btnForward" Content="→" HorizontalAlignment="Left" Margin="40,5,0,0" VerticalAlignment="Top" Width="20"/>
            <Button x:Name="btnDirUp" Content="↑" HorizontalAlignment="Left" Margin="91,5,0,0" VerticalAlignment="Top" Width="20" Click="btnDirUp_Click"/>
            <ProgressBar HorizontalAlignment="Left" Height="22" Margin="838,368,0,0" VerticalAlignment="Top" Width="422" x:Name="pgTesting"/>
        </Grid>
        <ListBox x:Name="lbSelectedItems" Margin="829,47,0,297" >

        </ListBox>

        <Button x:Name="btnTestReaction" Content="Start Backup" Width="136" Visibility="Visible" Click="btnTestReaction_Click" Margin="840,400,294,208"/>

        <Grid Margin="828,27,0,0" Height="20" VerticalAlignment="Top">

        </Grid>
        <TextBox x:Name="tbCurrentPath" Height="23" Margin="169,4,0,0" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" Width="1101" IsReadOnly="True" DataContextChanged="tbCurrentPath_DataContextChanged"/>
    </Grid>
</Window>


What I have tried:

A lot but I'm still a beginner
Posted
Updated 3-Apr-23 8:02am
v2
Comments
[no name] 3-Apr-23 11:31am    
Where are your "FileItems"; i.e. the listbox ItemsSource; which should contains items with "checkboxes". Seems you've included mostly "non-relevant" code.

1 solution

You are using MVVM. You can use DataBinding to track selection.

1. Wrap the Model:
C#
public class CheckItemModel : ObservableObject
{
    private bool isChecked;

    public bool IsChecked
    {
        get => isChecked;
        set => Set(ref isChecked, value);
    }

    public ObservableObject Model { get; set; }
}

2. Then in the MainViewModel listen for selection changes:
C#
public class MainViewModel : ViewModel, IDisposable
{
    public ObservableCollection<CheckItemModel> Models
    { get; set; } = new();
    
    public ObservableCollection<CheckItemModel> SelectedModels
    { get; set; } = new();

    public MainViewModel()
    {
        for (int i = 0; i < 100; i++)
        {
            var model = new CheckItemModel
            {
                Model = new WidgetModel
                {
                    Title = $"Widget {i}"
                }
            };

            // listen for changes
            model.PropertyChanged += OnItemPropertyChanged;

            Models.Add(model);
        }
    }

    // handle selection change
    private void OnItemPropertyChanged(
        object? sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName != nameof(CheckItemModel.IsChecked))
            return;

        var item = sender as CheckItemModel;

        if(item!.IsChecked)
            SelectedModels.Add(item);
        else
            SelectedModels.Remove(item);
    }

    // avoid memory leaks
    public void Dispose()
    {
        foreach (CheckItemModel model in Models)
        {
            model.PropertyChanged -= OnItemPropertyChanged;
        }
    }
}

3. The Window/View
XML
<Window.DataContext>
    <viewModels:MainViewModel />
</Window.DataContext>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Grid.Resources>
        <Style
            TargetType="ListBoxItem">

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate
                        TargetType="ListBoxItem">
                        <StackPanel Margin="8,4"
                            DataContext="{Binding Path=DataContext,
                            RelativeSource={RelativeSource
                                            AncestorType=ListBoxItem}}">
                            <CheckBox IsChecked="{Binding IsChecked}"
                                Content="{Binding Model.Title}" />
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

        </Style>
    </Grid.Resources>

    <ListBox ItemsSource="{Binding Models}" />
    <ListBox ItemsSource="{Binding SelectedModels}"
             Grid.Column="1"/>

</Grid>

As you select/deselect items, they are added or removed from the Selected Listbox.


Following are the support classes for DataBinding:
1. ObservableObject
C#
public class ObservableObject : INotifyPropertyChanged
{
    protected bool Set<TValue>
        (ref TValue field, TValue newValue,
         [CallerMemberName] string? propertyName = null)
    {
        if (EqualityComparer<TValue>
            .Default.Equals(field, newValue)) return false;

        field = newValue;
        OnPropertyChanged(propertyName);

        return true;
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged(
        [CallerMemberName] string? propertyName = null)
        => PropertyChanged?.Invoke(this,
            new PropertyChangedEventArgs(propertyName));
}

2. ViewModel:
C#
public class ViewModel : ObservableObject
{ /* skip */ }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900