XAML 检查列表中的复选框查看.net主页

hs1rzwqc  于 11个月前  发布在  .NET
关注(0)|答案(3)|浏览(123)

在我的项目maui我想要一个助手,以检查复选框时,我选择一个项目从列表视图与多个选择。我的列表视图在xaml:

<ListView x:Name="listViewComande"                  
           ItemSelected="listViewArticle_ItemSelected">
     <ListView.Header >        
     </ListView.Header>
     <ListView.ItemTemplate  >
         <DataTemplate >
             <ViewCell   >
                 <Grid RowDefinitions="Auto" 
                       ColumnDefinitions="5*,20*,45*,10*,10*,10*" 
                       Padding="3,10,3,10"  ColumnSpacing="8">
                       <CheckBox Grid.Row="1" Grid.Column="0" 
                       Color="LightGray"                     
                       x:Name="chekBoxListView" />                  
                     <Label Grid.Row="1" Grid.Column="2"  Text="{Binding DesignationComande}"      FontSize="13" VerticalTextAlignment="Center"
                          HorizontalTextAlignment="Start" MaxLines="1"  FontAttributes="None"/>                  
                 </Grid>
             </ViewCell>
         </DataTemplate>
     </ListView.ItemTemplate>
 </ListView>

public class ComandeTable
 {
    [PrimaryKey, AutoIncrement]
     public int ID { get; set; }
     public string ReferenceComande { get; set; }   
     public string DesignationComande { get; set; } 
 }

private void listViewArticle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{   
    if (e.SelectedItem != null)
    {       
    }
}

字符串
我使用了一个bool变量,但它不起作用

qoefvg9y

qoefvg9y1#

您的xaml演示了显示DesignationComande属性并在复选框更改时响应的意图(通过编程或用户交互)。这将需要ListView中绑定到这些属性的项的模型。
举例来说:


的数据

在xaml中完成绑定

DataTemplate中绑定IsChecked属性

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="checked_list_view.MainPage">
    <Grid
        RowDefinitions="*,*" >
        <ListView
            Grid.Row="0"
            x:Name="listViewComande"                  
            BackgroundColor="Azure">
            <ListView.ItemTemplate >
                <DataTemplate>
                    <ViewCell>
                        <Grid 
                            RowDefinitions="Auto" 
                            ColumnDefinitions="Auto,20*,45*,10*,10*,10*" 
                            Padding="3,10,3,10" 
                            ColumnSpacing="8">
                            <CheckBox 
                                IsChecked="{Binding IsChecked}"
                                Grid.Row="1" 
                                Grid.Column="0" 
                                Color="CornflowerBlue" />
                            <Label 
                                Grid.Row="1" 
                                Grid.Column="2"  
                                BackgroundColor="LightGreen"
                                Text="{Binding DesignationComande}"      
                                FontSize="13" VerticalTextAlignment="Center"                            
                                HorizontalTextAlignment="Start" MaxLines="1"  
                                HorizontalOptions="Fill"
                                FontAttributes="None"
                                Padding="10,0"/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Editor 
            Grid.Row="1"
            Text="{Binding EditorText}"/>
    </Grid>
</ContentPage>

字符串

ListView中的项目创建模型

此功能需要IsChecked的可绑定属性为复选框触发PropertyChanged事件。

class CheckableCommand : INotifyPropertyChanged
{
    public string DesignationComande { get; set; }
    public override string ToString() => DesignationComande;

    public bool IsChecked
    {
        get => _isChecked;
        set
        {
            if (!Equals(_isChecked, value))
            {
                _isChecked = value;
                OnPropertyChanged();
            }
        }
    }
    bool _isChecked = false;
    private void OnPropertyChanged([CallerMemberName]string caller = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

把它们粘在一起

在此示例中,MainPage的代码隐藏将ListViewItemsSource(您也可以在xaml中执行此操作)设置为CheckableCommand的可观察集合,并订阅项目的PropertyChanged通知。

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        BindingContext = this;
        InitializeComponent();
        listViewComande.ItemsSource = new ObservableCollection<CheckableCommand>
        {
            new CheckableCommand{ DesignationComande = "Command 1" },
            new CheckableCommand{ DesignationComande = "Command 2" },
            new CheckableCommand{ DesignationComande = "Command 3" },
        };
        foreach (CheckableCommand command in listViewComande.ItemsSource)
        {
            command.PropertyChanged += (sender, e) =>
            {
                switch (e.PropertyName) 
                {
                    case nameof(CheckableCommand.IsChecked):
                        var checkedCommands = 
                            listViewComande
                            .ItemsSource
                            .OfType<CheckableCommand>()
                            .Where (_ => _.IsChecked)
                            .ToList();
                        if(checkedCommands.Any())
                        {
                            EditorText = string.Join(Environment.NewLine, checkedCommands);
                        }
                        else
                        {
                            EditorText = "No checked commands at this time.";
                        }
                        break;
                }
            };            
            listViewComande.ItemSelected += (sender, e) =>
            {
                // Option to check the checkbox when item is selected.
                if (e.SelectedItem is CheckableCommand cmd) cmd.IsChecked = true;
            };
        }
        EditorText = "Hello, I'll be keeping track of your checked commands.";
    }
    public string EditorText
    {
        get => _editorText;
        set
        {
            if (!Equals(_editorText, value))
            {
                _editorText = value;
                OnPropertyChanged();
            }
        }
    }
    string _editorText = string.Empty;
}

h7appiyu

h7appiyu2#

我的理解是,当你在listView中选择一个项目时,你想检查一个Checkbox

private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
    var viewCell = ((ListView)sender);
    var checkbox = viewCell.GetVisualTreeDescendants().Where(x => x.GetType() == typeof(CheckBox));
    var currentCheckbox = (CheckBox)checkbox.ElementAt(e.ItemIndex);
    //var currentCheckbox = (CheckBox)checkbox.ToList()[e.ItemIndex];
    if (!currentCheckbox.IsChecked)
        currentCheckbox.IsChecked = true;
    else
        currentCheckbox.IsChecked = false;
}

字符串
注意一件事,这里ListView_ItemTappedItemTapped而不是ItemSelected

f3temu5u

f3temu5u3#

我建议创建两个视图模型:

  • RankedViewModel-对于集合中的每个项目
  • MainViewModel -父视图模型,保存ObservableCollection和所选项的动态列表

我们可以将每个项目的CheckedViewModel.OnPropertyChanged订阅到父MainViewModel,以便父视图模型在IsChecked发生变化时得到通知,并根据需要重新计算SelectedItems
MainPage.xaml.cs中,我们实现了ListView_ItemTapped来操作集合视图模型。

// MauiProgram.cs
builder.Services.AddTransient<MainViewModel>();
builder.Services.AddTransient<MainPage>();
// CheckedViewModel.cs
public partial class CheckedViewModel : ObservableObject
{
    [ObservableProperty]
    private bool _isChecked = false;

    [ObservableProperty]
    private string _commandText = string.Empty;
}
// MainViewModel.cs
public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<CheckedViewModel> _checkedItems = new()
    {
        new CheckedViewModel { CommandText = "Command 1" },
        new CheckedViewModel { CommandText = "Command 2" },
        new CheckedViewModel { CommandText = "Command 3" },
    };

    public List<CheckedViewModel> SelectedItems => CheckedItems.Where(x => x.IsChecked).ToList();

    public MainViewModel()
    {
        foreach (var item in CheckedItems)
        {
            item.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(CheckedViewModel.IsChecked))
                {
                    OnPropertyChanged(nameof(SelectedItems));
                }
            };
        }
    }
}
<!-- MainPage.xaml -->
<VerticalStackLayout x:DataType="{x:Type local:MainViewModel}">
    <ListView x:Name="myView"
              ItemsSource="{Binding CheckedItems}"
              ItemTapped="myView_ItemTapped">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="{x:Type local:CheckedViewModel}">
                <ViewCell>
                    <HorizontalStackLayout>
                        <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" />
                        <Label Text="{Binding CommandText}" />
                    </HorizontalStackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <Label Text="{Binding SelectedItems.Count, StringFormat='{0} commands checked'}" />
    <ListView ItemsSource="{Binding SelectedItems}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="{x:Type local:CheckedViewModel}">
                <ViewCell>
                    <Label Text="{Binding CommandText}" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</VerticalStackLayout>
// MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    MainViewModel VM;

    public MainPage(MainViewModel VM)
    {
        InitializeComponent();
        this.VM = VM;
        BindingContext = VM;
    }

    private void myView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        VM.CheckedItems[e.ItemIndex].IsChecked = !VM.CheckedItems[e.ItemIndex].IsChecked;
    }
}

相关问题