我在TemplateStudio for WinUI的基础上用WinUI
和Microsoft.Toolkit.Mvvm
创建了一个简单的ListView
。
我尝试实现一个包含水果名称的简单ListView
,第二个ListView
从第一个SelectedItems
获得SelectedItems
,最后一个TextBox
包含选定项的计数。
主页.xaml
<Page
x:Class="ListViewWinUISample.Views.MainPage"
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:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
mc:Ignorable="d">
<Grid x:Name="ContentArea" Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="150" />
<RowDefinition Height="25" />
<RowDefinition Height="150" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="Fruits list :" Style="{StaticResource PageTitleStyle}" />
<ListView Grid.Row="1" x:Name="LvwFruits" ItemsSource="{x:Bind ViewModel.ListFruits}" BorderBrush="#212121" SelectionMode="Multiple">
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:InvokeCommandAction Command="{x:Bind ViewModel.GetSelectedFruits}" CommandParameter="{Binding SelectedItems, ElementName=LvwFruits}"/>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
</ListView>
<TextBlock Grid.Row="2" Text="Selected fruits :" Style="{StaticResource PageTitleStyle}" />
<ListView Grid.Row="3" x:Name="LvwSelectedFruits" ItemsSource="{x:Bind ViewModel.ListSelectedFruits}" BorderBrush="#212121"/>
<StackPanel Grid.Row="4" Orientation="Horizontal">
<TextBlock Text="Count selected fruits : " VerticalAlignment="Center"/>
<TextBox Text="{Binding SelectedItems.Count, ElementName=LvwFruits}" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
</Page>
主视图模型.cs
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace ListViewWinUISample.ViewModels;
public class MainViewModel : ObservableRecipient
{
public List<string> ListFruits;
public List<string> ListSelectedFruits;
public RelayCommand<IList> GetSelectedFruits { get; set; }
public MainViewModel()
{
GetSelectedFruits = new RelayCommand<IList>(GetSelectedFruitsMethod);
var fruits = new List<string>
{
"Apple",
"Banana",
"Strawberry"
};
ListFruits = fruits;
}
private void GetSelectedFruitsMethod(IList selectedFruits)
{
Debug.WriteLine("Command successfully executed");
var listSelectedFruits = new List<string>();
foreach (var item in selectedFruits)
{
listSelectedFruits.Add(item.ToString());
Debug.WriteLine("selected fruit : " + item.ToString());
}
}
}
GetSelectedFruitsMethod
已成功启动,但GetSelectedFruitsMethod
中的参数IList selectedFruits
始终为null
,即使我在XAML中将其作为CommandParameter
传递,我也不知道如何从视图中获取SelectedItems
参数。
谢谢,问候。
1条答案
按热度按时间xytpbqjk1#
您可以像这样创建自定义控件:
列表视图示例.cs
并像这样使用它:
主页.xaml
主页.xaml.cs