如何获取复选框值而不在wpf中获取disconnecteditem?

时间:2018-04-13 05:36:24

标签: wpf image checkbox listbox

WPF:

<Window x:Class="simple.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:simple"
    Title="MainWindow" ResizeMode="NoResize"  Height="500" Width="530">
<Window.Resources>
    <Style TargetType="{x:Type ListBox}">
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border BorderBrush="Black" BorderThickness="4" CornerRadius="5" Margin="6" >
                        <CheckBox x:Name="CheckBox" Checked="CheckBoxChecked" Unchecked="CheckBoxUnChecked"  IsChecked="{Binding  ElementName=BtnSelectAllOrUnSelectAll,Path=IsChecked,Mode=OneWay}">
                            <Image Source="{Binding }" Stretch="Fill" Width="100" Height="120" >
                                <Image.ToolTip>
                                    <StackPanel>
                                        <TextBlock Text="{Binding PixelWidth, StringFormat=Width: {0}}"/>
                                        <TextBlock Text="{Binding PixelHeight, StringFormat=Height: {0}}"/>
                                        <TextBlock Text="{Binding}" />
                                    </StackPanel>
                                </Image.ToolTip>
                            </Image>
                        </CheckBox>
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapPanel />
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled"/>
    </Style>
</Window.Resources>
<Window.DataContext>
    <ObjectDataProvider ObjectType="{x:Type local:MainWindow}" MethodName="LoadImages" />
</Window.DataContext>
<Grid Margin="0,0,0,16" x:Name="grid">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListBox x:Name="ImageList"  ItemsSource="{Binding}"   Margin="-50,-8,93,0" RenderTransformOrigin="0.5,0.5" Height="289" VerticalAlignment="Top" >
            <ListBox.RenderTransform>                   
                <TransformGroup>
                    <ScaleTransform ScaleX="0.975" ScaleY="0.997"/>
                    <SkewTransform AngleY="-8.98" AngleX="9.705"/>
                    <RotateTransform Angle="9.419"/>
                    <TranslateTransform Y="76.889" X="64.258"/>
                </TransformGroup>
            </ListBox.RenderTransform>
        </ListBox>
    <Button FontWeight="Bold" IsEnabled="False" Content="Download" Name="BtnDownloadImages" Click="DownloadImages"  HorizontalAlignment="Left" Margin="286,383,0,0" VerticalAlignment="Top" Width="115" Height="57" RenderTransformOrigin="0.986,1.365"/>
    <ToggleButton FontWeight="Bold" x:Name="BtnSelectAllOrUnSelectAll" Content="Select/Unselect" HorizontalAlignment="Left" Margin="53,383,0,0" VerticalAlignment="Top" Width="115" Height="57" RenderTransformOrigin="0.986,1.365"/>
    <!--<ToolBarPanel HorizontalAlignment="Left" Height="17" Margin="315,366,0,0" VerticalAlignment="Top" Width="100"/>-->
    <Button FontWeight="Bold" Height="21" HorizontalAlignment="Right" Margin="0,0,48,398" Name="BtnNext" VerticalAlignment="Bottom" Width="45" Content="Next" Click="ButtonClickNext" RenderTransformOrigin="0.289,0.571" />
    <Button  FontWeight="Bold" Content="Previous" Name="BtnPrevious" IsEnabled="False" HorizontalAlignment="Left" Margin="263,21,0,0" Click="ButtonClickPrevious" VerticalAlignment="Top" Width="54"/>
    <StackPanel  x:Name="loadButtons" HorizontalAlignment="Center"  Orientation = "Horizontal" Height = "22" VerticalAlignment = "Top" Margin = "331,22,81,0" Width="110">

    </StackPanel>
    <Label FontWeight="Bold"  Name="NumberOfSelectedImages" HorizontalAlignment="Left" Margin="24,36,0,0" VerticalAlignment="Top" ContentStringFormat="{}{0:0.##}" />
</Grid> </Window>

C#:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;
using System.Xml;

namespace simple
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.DataContext = check;
            Loaded += MyWindow_Loaded;
        }

        public int buttonCount = 4;
        public int btnPreviousImage = 0;
        public int buttonCountPerPage = 4;
        public int pageCount = 0;
        List<string> checkboxCheckedList = new List<string>();
        private int pageIndex = 1;
        int checkboxCheckedCount = 0;
        public static List<BitmapImage> imgcloudinaryImages = new List<BitmapImage>();
        public static List<BitmapImage> copycloudinaryImages = new List<BitmapImage>();
        int xmlUrlCount = 0;



        public List<BitmapImage> LoadImages()
        {
            List<string> xmldataCount = new List<string>();
             //List of images
            List<BitmapImage> loadImagesPerPage = new List<BitmapImage>();  //

            bool status = false;
            XmlTextReader xmldatareader = new XmlTextReader(ConfigurationManager.AppSettings["XmlFileUrl"]);
            while (xmldatareader.Read())
            {
                if (xmldatareader.Name == "collection")
                {

                    if (status)
                        status = false;
                    else
                        status = true;
                }

                if (status && (xmldatareader.NodeType == XmlNodeType.Element) && (xmldatareader.Name == "image"))
                {
                    if (xmldatareader.HasAttributes)
                    {
                        xmldataCount.Add(xmldatareader.GetAttribute("url"));

                    }

                }
            }
                foreach (var URL in xmldataCount)
                {
                    var imgBitmap = new BitmapImage(new Uri(URL));
                    imgcloudinaryImages.Add(imgBitmap);
                }


            foreach (var image in imgcloudinaryImages)
            {
                xmlUrlCount += 1;
                loadImagesPerPage.Add(image);
                if (xmlUrlCount == int.Parse(ConfigurationManager.AppSettings["LoadImagesPerPage"]))
                    break;
            }
            copycloudinaryImages = imgcloudinaryImages;
            return loadImagesPerPage;
        }

        private void MyWindow_Loaded(object sender, RoutedEventArgs e)
        {
            int totalImages = copycloudinaryImages.Count;
            int pageSize = 6;
            if (totalImages % pageSize == 0)
            {
                pageCount = totalImages / pageSize;
            }
            else
            {
                pageCount = (totalImages / pageSize) + 1;
            }
            loadButtons.Children.Clear();

            for (int i = 0; i < pageCount; i++)
            {
                Button button = new Button()
                {
                    Content = (i + 1).ToString(),
                    Tag = i
                };
                button.Width = 20;
                button.Height = 20;
                button.Click += new RoutedEventHandler(LoadButton);
                loadButtons.Children.Add(button);
            }
            if (pageCount <= 4)
                BtnNext.IsEnabled = false;
        }

        private void DownloadImages(object sender, RoutedEventArgs e)
        {
            try
            {

                Array.ForEach(Directory.GetFiles(ConfigurationManager.AppSettings["LocalFileUrl"]), File.Delete);
                foreach (var
 source in checkboxCheckedList)
                {
                    int j = 1;
                    string remoteFileUrl = source;
                    string localFileName = ConfigurationManager.AppSettings["LocalFileUrl"] + "download" + j + ".JPG";
                    WebClient webClient = new WebClient();
                    while (File.Exists(localFileName))
                    {
                        j += 1;
                        localFileName = ConfigurationManager.AppSettings["LocalFileUrl"] + "download" + j + ".JPG";
                    }
                    webClient.DownloadFile(remoteFileUrl, localFileName);
                }
                if (checkboxCheckedList.Count > 0)
                {
                    MessageBox.Show("Image Downloaded Successfully");
                }
                else
                {
                    MessageBox.Show("No Image Selected");
                }
            }
            catch (Exception e1)
            {

                MessageBox.Show(e1.Message);
            }

        }
        public List<CheckBox> check = new List<CheckBox>();
        private void CheckBoxChecked(object sender, RoutedEventArgs e)
        {

            copycloudinaryImages = imgcloudinaryImages;
            BtnDownloadImages.IsEnabled = true;
            string imagepath = Convert.ToString(((CheckBox)sender).DataContext);

            if (imagepath == "{DisconnectedItem}")
            {
                checkboxCheckedCount += 1;
            }
            else
            {

                if (checkboxCheckedCount < 30)
                {

                    checkboxCheckedList.Add(imagepath);
                    checkboxCheckedCount += 1;
                    NumberOfSelectedImages.Content = checkboxCheckedCount + "  Item Selected";

                }
                else
                {
                    if (((CheckBox)sender).IsChecked == true)
                    {
                        checkboxCheckedCount += 1;
                        CheckBox myCheckBox = new CheckBox();
                        myCheckBox = ((CheckBox)sender);
                        check.Add(myCheckBox);
                        ((CheckBox)sender).IsChecked = false;
                        ((CheckBox)sender).IsEnabled = false;

                    }
                }
            }
        }

        private void CheckBoxUnChecked(object sender, RoutedEventArgs e)
        {
            checkboxCheckedCount -= 1;

            if (checkboxCheckedCount <= 29)
            {
                if (checkboxCheckedCount == 0)
                {

                }
                else
                {
                    //checkboxCheckedCount -= 1;
                    foreach (var item in check)
                    {
                        item.IsEnabled = true;
                    }
                }
            }
            else
            {
                foreach (var item in check)
                {
                    item.IsEnabled = false;
                }
            }
            string imagepath = Convert.ToString(((CheckBox)sender).DataContext);
            checkboxCheckedList.Remove(imagepath);
            NumberOfSelectedImages.Content = checkboxCheckedCount + "  Item Selected";
        }

        private void ButtonClickNext(object sender, System.EventArgs e)
        {
            int totalImages = copycloudinaryImages.Count;
            int pageSize = 6;
            if (totalImages % pageSize == 0)
            {
                pageCount = totalImages / pageSize;
            }
            else
            {
                pageCount = (totalImages / pageSize) + 1;
            }
            int noOfButtonsLoad = 4;
            loadButtons.Children.Clear();
            if (BtnPrevious.IsEnabled == false)
            {
                buttonCount = 4;
                buttonCountPerPage = 4;
            }

            if ((noOfButtonsLoad*pageSize) <=totalImages)
            {

                for (int i = 1; i <= noOfButtonsLoad; i++)
                {
                    if (pageCount == buttonCount + i)
                    {
                        BtnNext.IsEnabled = false;
                        break;
                    }
                    if (buttonCountPerPage == pageCount - 1)
                    {

                        break;
                    }
                    Button button = new Button()
                    {
                        Content = (i + buttonCount).ToString(),
                        Tag = i + buttonCount
                    };
                    button.Width = 20;
                    button.Height = 20;
                    button.Click += new RoutedEventHandler(LoadButton);
                    loadButtons.Children.Add(button);
                    btnPreviousImage = i;
                    buttonCountPerPage += 1;

                    if (i == 4)
                        buttonCount += i;
                }
            }
            BtnPrevious.IsEnabled = true;

        }

        void LoadButton(object sender, RoutedEventArgs e)
        {
            pageIndex = (int)(sender as Button).Tag;
            ImageList.DataContext = copycloudinaryImages.Skip(6 * pageIndex).Take(6).ToList();
           // ImageList.UpdateLayout();
        }


        private void ButtonClickPrevious(object sender, System.EventArgs e)
        {
            BtnNext.IsEnabled = true;
            int back = 0;
            loadButtons.Children.Clear();
            if (buttonCountPerPage - 4 <= 0)
            {
                back = buttonCountPerPage;
                for (int i = 1; i <= back; i++)
                {

                    Button button = new Button()
                    {
                        Content = (i).ToString(),
                        Tag = i
                    };
                    button.Width = 20;
                    button.Height = 20;
                    button.Click += new RoutedEventHandler(LoadButton);
                    loadButtons.Children.Add(button);
                }
                BtnPrevious.IsEnabled = false;
            }
            else
            {

                back = buttonCountPerPage - 4;
                for (int i = back; i <= buttonCountPerPage - 1; i++)
                {

                    Button button = new Button()
                    {
                        Content = (i).ToString(),
                        Tag = i
                    };
                    button.Width = 20;
                    button.Height = 20;
                    button.Click += new RoutedEventHandler(LoadButton);
                    loadButtons.Children.Add(button);
                }
                buttonCountPerPage -= 4;
            }
            btnPreviousImage -= 4;
            if (back == 1)
                BtnPrevious.IsEnabled = false;
            if (BtnPrevious.IsEnabled == false)
                buttonCount = 0;
        }
    }
}

当我单击选择所有按钮时,它会选择所有图像,但它仅添加6个图像用于列表。请帮我。当我尝试在checkbox_checked事件中调试代码时,我使用select / unselect按钮选择所有图像,但是一些图像与datacontext断开连接。 DisconncetedItems来自不同的datacontext。如何解决它。 请帮帮我

1 个答案:

答案 0 :(得分:0)

ListBox默认使用UI虚拟化。将该属性设置为false以停止获取断开连接的项目。

<ListBox VirtualizingStackPanel.IsVirtualizing="False"/>