UWP:在按钮单击事件上取消选中 ListView 内的复选框

Posted

技术标签:

【中文标题】UWP:在按钮单击事件上取消选中 ListView 内的复选框【英文标题】:UWP:Uncheck checkboxes inside ListView on Button Click Event 【发布时间】:2019-10-18 05:27:00 【问题描述】:

我正在尝试清除 popup=>ListView on Button Click Event 中的选中复选框。

我尝试循环 listview 并将属性设置为 false,但它不起作用。

在此处输入代码 x:Class="UC.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="使用:UC" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 麦克:忽略=“d” xmlns:mvsc="使用:UC.Models"

Background="ThemeResource ApplicationPageBackgroundThemeBrush">

<Grid>
    <StackPanel>
        <Button x:Name="btn_Add" Content="Add"  Margin="420,10,10,0" Click="Btn_Add_Click"/>
    </StackPanel>
    <StackPanel Margin="10,50,10,0">
        <TextBlock Text="Selected List" Margin="10" HorizontalAlignment="Left"  VerticalAlignment="Top" />
        <Border BorderBrush="StaticResource ApplicationForegroundThemeBrush"
                Background="StaticResource ApplicationPageBackgroundThemeBrush"
                BorderThickness="1"  Margin="10,0,800,5" Height="300">
            <ListView  x:Name="lstViewSelectedData" ScrollViewer.VerticalScrollBarVisibility="Auto"
               ScrollViewer.VerticalScrollMode="Enabled">
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="mvsc:SelectedDataModel">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock VerticalAlignment="Center" x:Name="txtSelectedData" Text="x:Bind Message"></TextBlock>
                            <AppBarButton VerticalAlignment="Bottom" Click="AppBarButton_Click" Icon="Delete" 
                                  Tag="x:Bind Id, Mode=OneWay" >
                            </AppBarButton>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </Border>

    </StackPanel>
    <Popup x:Name="popup1" VerticalOffset="10" HorizontalOffset="450" IsLightDismissEnabled="True" 
           HorizontalAlignment="Stretch" Margin="50" VerticalAlignment="Stretch">

        <Border BorderBrush="StaticResource ApplicationForegroundThemeBrush" 
                Background="StaticResource ApplicationPageBackgroundThemeBrush"
                BorderThickness="1" Width="450" Height="400" >
            <StackPanel x:Name="stkpnl1" Orientation="Vertical">
                <TextBox x:Name="txtSearch" Header="Filter" Margin="10"  
                     PlaceholderText="Search list" TextChanging="TxtSearch_TextChanging" />


                <ListView x:Name="lstView" Margin="30" Height="200" 
                      ScrollViewer.VerticalScrollBarVisibility="Auto"
                      ScrollViewer.VerticalScrollMode="Enabled">
                    <ListView.ItemTemplate >
                        <DataTemplate x:DataType="mvsc:SelectedDataModel" >
                            <CheckBox x:Name="chkBox" 

                          FlowDirection="LeftToRight"  
                          Tag="x:Bind Id, Mode=TwoWay" 
                          Content="x:Bind Message, Mode=TwoWay" IsChecked="x:Bind IsFavorite,Mode=TwoWay"
                          Checked="ChkBox_Checked" Unchecked="ChkBox_Unchecked" IsHitTestVisible="True"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <StackPanel Orientation="Horizontal" Grid.Row="2" Grid.Column="1" FlowDirection="LeftToRight" >
                    <Button x:Name="btnAdd" Content="Select" Click="BtnAdd_Click" Margin="10" />
                    <Button x:Name="btnCancel" Content="Close"  Click="BtnCancel_Click"/>


                </StackPanel>
            </StackPanel>

        </Border>
    </Popup>
</Grid>

 public sealed partial class MainPage : Page
    
        public SelectedDataModel SelectedData
        
            get  return (SelectedDataModel)GetValue(SelectedDataProperty); 
            set  SetValue(SelectedDataProperty, value); 
        

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedDataProperty =
                        DependencyProperty.Register("SelectedData", typeof(int), typeof(SelectedDataModel), null);

        public AllDataModel AllDataList
        
            get  return (AllDataModel)GetValue(AllDataListProperty); 
            set  SetValue(AllDataListProperty, value); 
        

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AllDataListProperty =
                        DependencyProperty.Register("AllDataList", typeof(int), typeof(AllDataModel), null);

        List<SelectedDataModel> listData = new List<SelectedDataModel>();
        List<SelectedDataModel> temp = new List<SelectedDataModel>();
        List<SelectedDataModel> temp1 = new List<SelectedDataModel>();
        List<SelectedDataModel> selectedData = new List<SelectedDataModel>();

        public MainPage()
        
            this.InitializeComponent();
            lstView.ItemsSource = GetData();
            //lstViewSelectedData.ItemsSource = GetSelectedData();
            temp = listData;
        
        public List<SelectedDataModel> GetData()
        
            listData.Add(new SelectedDataModel  Id = 1, Message = "One" );
            listData.Add(new SelectedDataModel  Id = 2, Message = "Two" );
            listData.Add(new SelectedDataModel  Id = 3, Message = "Three" );
            listData.Add(new SelectedDataModel  Id = 4, Message = "Four" );
            listData.Add(new SelectedDataModel  Id = 5, Message = "Five" );
            listData.Add(new SelectedDataModel  Id = 6, Message = "Six" );
            listData.Add(new SelectedDataModel  Id = 7, Message = "Seven" );
            listData.Add(new SelectedDataModel  Id = 8, Message = "Eight" );

            return listData;
        

        private async void BtnAdd_Click(object sender, RoutedEventArgs e)
        
            if (selectedData.Count == 0)
            
                ContentDialog dialog = new ContentDialog();
                dialog.Title = "Not Selected";
                dialog.Content = "Please Select Atlease One Entry";
                dialog.CloseButtonText = "Close";
                await dialog.ShowAsync();
            
            else
            
                lstViewSelectedData.ItemsSource = null;
                var dt = selectedData;
                lstViewSelectedData.ItemsSource = dt;
                //this.selectedData.ForEach(x => x.IsFavorite = false);
                //this.listData.ForEach(x => x.IsFavorite = false);
                //temp1 = dt;
                popup1.IsOpen = false;



                //foreach (SelectedDataModel row in lstView.Items.ToList())
                //
                //    //CheckBox box = row.FindName("chkSelect") as CheckBox;
                //    if (row.IsFavorite == true)
                //    
                //        row.IsFavorite = false;
                //      //  listData.Remove(listData.First(X => X.Id == row.Id));
                //        //Logic to delete the row 
                //    

                //
                for (int i = 0; i < lstView.Items.Count; i++)
                
                    ListViewItem lvi = (ListViewItem)lstView.ItemContainerGenerator.ContainerFromItem(lstView.Items[i]);

                    if (lvi != null)
                    
                        //CheckBox c = lvi.FindChildByType<CheckBox>();
                        //c.IsChecked = true;
                    
                
            

        
        private void TxtSearch_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
        
            listData = temp;

            if (!string.IsNullOrEmpty(txtSearch.Text))
            
                listData = listData.Where(x => x.Message.ToUpper().Contains(txtSearch.Text.ToUpper())).ToList();
                if (listData.Count > 0)
                
                    lstView.ItemsSource = listData;
                
                else
                
                    lstView.ItemsSource = temp;
                
            
            else
            
                lstView.ItemsSource = temp;
            
        
        private void ChkBox_Checked(object sender, RoutedEventArgs e)
        
            var chkBox = sender as CheckBox;
            //throwing an exception System.NullReferenceException: 'Object reference not set to an instance of an object.'
            selectedData.Add(listData.First(x => x.Id == int.Parse(chkBox.Tag.ToString())));
           // listData.Remove(listData.First(X => X.Id == int.Parse(chkBox.Tag.ToString())));

            //selectedData.Clear();


        


        private void ChkBox_Unchecked(object sender, RoutedEventArgs e)
        
            var chkBox = sender as CheckBox;
            selectedData.Remove(listData.First(X => X.Id == int.Parse(chkBox.Tag.ToString())));

        
        private void BtnAddData_Click(object sender, RoutedEventArgs e)
        
            //popup2.IsOpen = false;
            popup1.IsOpen = true;
        
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        
            popup1.IsOpen = false;
        
        private void Btn_Add_Click(object sender, RoutedEventArgs e)
        


            popup1.IsOpen = true;
        
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        
            AppBarButton delButton = sender as AppBarButton;
            ContentDialog dialog = new ContentDialog();
            dialog.Content = "Do You Want To Remove..?";
            dialog.PrimaryButtonText = "Yes";
            dialog.SecondaryButtonText = "No";
            dialog.Title = "Remove";
            ContentDialogResult result = await dialog.ShowAsync();
            if (result == ContentDialogResult.Primary)
            
                //var isRemoved = temp.Remove(listData.First(x => x.id == int.Parse(delButton.Tag.ToString())));

                //List<Info> temp1 = new List<Info>();
                //foreach (var item in temp)
                //
                //    temp1.Add(item);
                //
                //lstViewSelectedData.ItemsSource = temp1;
                var temp2 = selectedData;
                temp2.Remove(temp1.First(x => x.Id == int.Parse(delButton.Tag.ToString())));
                lstViewSelectedData.ItemsSource = null;
                lstViewSelectedData.ItemsSource = temp2;
            
        

    

我只想在按钮单击事件 UWP 上清除列表视图中的选中项目。

【问题讨论】:

【参考方案1】:

我尝试循环 listview 并将属性设置为 false,但它不起作用。

您的 CheckBox 绑定到 IsFavorite 属性。所以,如果你想取消选中它,你只需要更新IsFavorite 属性的值。要在属性值更改时更新 UI,您的 SelectedDataModel 类需要实现 INotifyPropertyChanged Interface。

public class SelectedDataModel : INotifyPropertyChanged

    private int _Id;

    public int Id
    
        get  return _Id; 
        set
        
            if (_Id != value)
            
                _Id = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Id"));
            
        
    

    private string _Message;

    public string Message
    
        get  return _Message; 
        set
        
            if (_Message != value)
            
                _Message = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Message"));
            
        
    

    private bool _IsFavorite;

    public bool IsFavorite
    
        get  return _IsFavorite; 
        set
        
            if (_IsFavorite != value)
            
                _IsFavorite = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsFavorite"));
            
        
    

    public event PropertyChangedEventHandler PropertyChanged;

然后,在您的按钮单击事件处理程序中,您只需将 listData 中每个项目的 IsFavorite 更改为 false。

foreach (var item in listData)

    item.IsFavorite = false;

【讨论】:

以上是关于UWP:在按钮单击事件上取消选中 ListView 内的复选框的主要内容,如果未能解决你的问题,请参考以下文章

UWP ListView 绑定 单击 选中项 颜色

mfc如何设置取消按钮的默认选中以及单击后的默认选中?

vb.net 点击按钮选中listview最后一行

取消选择 ListView 中的项目

如何使用uwp中的全选复选框创建带有复选框项目的列表视图

从 ListViewItem 单击 UWP 按钮