0

我的 UWP 应用程序中有一个模板化控件,其中包含一个 ListView。ListView 在运行时填充。

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Renderer"
    xmlns:triggers="using:Microsoft.Toolkit.Uwp.UI.Triggers">
    <Style x:Key="RendererDefaultStyle" TargetType="local:Renderer" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:Renderer">
                    <Grid>
                    ....
                        <ListView x:Name="AnnotsList" Margin="0,12,0,0" SelectionMode="None" Grid.Row="1" VerticalAlignment="Stretch" IsItemClickEnabled="True" Visibility="{Binding IsAnnotationsListOpen, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ItemContainerStyle="{StaticResource AnnotationsListViewItemStyle}">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition />
                                            <ColumnDefinition Width="Auto" />
                                        </Grid.ColumnDefinitions>
                                        <StackPanel Orientation="Vertical">
                                            <TextBlock Text="{Binding}" />
                                            <TextBlock Text="{Binding DisplayTitle}" Margin="20,0,0,10" FontSize="12" TextWrapping="WrapWholeWords" Visibility="Visible" />
                                        </StackPanel>
                                        <CommandBar Grid.Column="1">
                                            <CommandBar.SecondaryCommands>
                                                <AppBarElementContainer>
                                                    <StackPanel Orientation="Horizontal">
                                                        <Button x:Name="btn_RemoveFromList" DataContext="{Binding}">
                                                            <Button.Content>
                                                                <SymbolIcon Symbol="Delete" />
                                                            </Button.Content>
                                                            <ToolTipService.ToolTip>
                                                                <ToolTip Content="Delete" Placement="Mouse" />
                                                            </ToolTipService.ToolTip>
                                                        </Button>
                                                    </StackPanel>
                                                </AppBarElementContainer>
                                            </CommandBar.SecondaryCommands>
                                        </CommandBar>
                                    </Grid>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.GroupStyle>
                                <GroupStyle >
                                    <GroupStyle.HeaderTemplate>
                                        <DataTemplate>
                                            <Border AutomationProperties.Name="{Binding Key}">
                                                <TextBlock Text="{Binding Key}" Style="{ThemeResource TitleTextBlockStyle}"/>
                                            </Border>
                                        </DataTemplate>
                                    </GroupStyle.HeaderTemplate>
                                </GroupStyle>
                            </ListView.GroupStyle>
                        </ListView>
                    ....
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="local:Renderer" BasedOn="{StaticResource RendererDefaultStyle}"/>
</ResourceDictionary>

我试图将点击事件绑定到这样的按钮,但由于它是动态生成的,所以它不起作用。

public sealed class Renderer: Control, IDisposable
{
  ....
  private void UpdateAnnotationsListView() 
  {
    (GetTemplateChild("AnnotsList") as ListView).ItemsSource = null;

    var source = AnnotationAdapter.GetGroupedAnnotations(); // ObservableCollection<ListViewGroupInfo>

    var viewSource = new CollectionViewSource 
    {
      IsSourceGrouped = true, Source = source
    };
    (GetTemplateChild("AnnotsList") as ListView).ItemsSource = viewSource.View;

    if (viewSource.View.Count > 0) 
    {
      (GetTemplateChild("btn_RemoveFromList") as Button).Click -= null;
      (GetTemplateChild("btn_RemoveFromList") as Button).Click += async delegate(object sender, RoutedEventArgs e) 
      {
        await OpenRemoveConfirmationAsync();
      };
    }
  }
  ....
}

列表源是一个ObservableCollection类型

public class ListViewGroupInfo: List < object >
{
  public ListViewGroupInfo() {}

  public ListViewGroupInfo(IEnumerable < object > items): base(items) {}

  public object Key 
  {
    get;
    set;
  }
}

列表源的结构使得我可以相应地对列表项进行分组。

这是呈现的 ListView 的示例,以获取更多上下文。 在此处输入图像描述

删除按钮是我在这里尝试使用的按钮。

我想将一个方法绑定到 ListView 中这些按钮的单击事件。

我不能使用名称属性,因为随着列表的增长可能会有多个按钮。

由于此按钮位于模板化控件中并在运行时生成,因此我找不到将方法绑定到单击事件的方法。

我的猜测是我必须将命令绑定到按钮。但我也找不到这样做的方法。

我没有在模板控件中使用 MVVM 模式。

谁能帮我解决这个问题?任何帮助深表感谢。

4

2 回答 2

0

经过大量的研究和反复试验,我最终采用了 @nico-zhu-msft 建议的不同方法。

基本上,我将 ListView 移动到单独的用户控件并观察父模板控件的属性更改。为了将数据绑定到ListView使用的视图模型。

AssnotationsList.xaml

<UserControl
    x:Class="PDF.Renderer.AnnotationsList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PDF.Renderer"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:viewmodels="using:PDF.Renderer.ViewModels"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <UserControl.DataContext>
        <viewmodels:AnnotationsListViewModel />
    </UserControl.DataContext>
    
    <UserControl.Resources>
        <Style x:Key="AnnotationsListViewItemStyle" TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="VerticalContentAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
    </UserControl.Resources>

    <ListView SelectionMode="None" VerticalAlignment="Stretch" IsItemClickEnabled="True" ItemContainerStyle="{StaticResource AnnotationsListViewItemStyle}" ItemsSource="{Binding AnnotationsList}" ItemClick="AnnotationListViewItemClick">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding}" />
                    <TextBlock Text="{Binding DisplayTitle}" Margin="20,0,0,10" FontSize="12" TextWrapping="WrapWholeWords" Visibility="Visible" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>

        <ListView.GroupStyle>
            <GroupStyle >
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <Border AutomationProperties.Name="{Binding Key}">
                            <TextBlock Text="{Binding Key}" Style="{ThemeResource TitleTextBlockStyle}"/>
                        </Border>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>
</UserControl>

AnnotationsList.xaml.cs

public sealed partial class AnnotationsList : UserControl, INotifyPropertyChanged
{
    public AnnotationsList()
    {
        this.InitializeComponent();
    }

    private BaseAnnotation selectedAnnotation = null;

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public ICollectionView AnnotationsListSource
    {
        get { return (ICollectionView)GetValue(AnnotationsListSourceProperty); }
        set { SetValue(AnnotationsListSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AnnotationsListSourceProperty =
        DependencyProperty.Register(nameof(AnnotationsListSourceProperty), typeof(ICollectionView), typeof(AnnotationsList), new PropertyMetadata(null, new PropertyChangedCallback(OnAnnotationsListSourceChanged)));

    private static void OnAnnotationsListSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (object.Equals(e.NewValue, e.OldValue) || e.NewValue is null)
            return;

        d.RegisterPropertyChangedCallback(AnnotationsListSourceProperty, CaptureAnnotationListSource);
    }

    private static void CaptureAnnotationListSource(DependencyObject sender, DependencyProperty dp) => (sender as AnnotationsList).SetAnnotationsListSource(sender.GetValue(dp) as ICollectionView);

    private void SetAnnotationsListSource(ICollectionView annotationsCollection) => (this.DataContext as AnnotationsListViewModel).AnnotationsList = annotationsCollection;

    public BaseAnnotation SelectedAnnotation
    {
        get { return selectedAnnotation; }
        set { if (value != selectedAnnotation && value != null) { selectedAnnotation = value; OnPropertyChanged(nameof(SelectedAnnotation)); }; }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedAnnotationProperty =
        DependencyProperty.Register(nameof(SelectedAnnotationProperty), typeof(BaseAnnotation), typeof(AnnotationsList), new PropertyMetadata(null));

    private void AnnotationListViewItemClick(object sender, ItemClickEventArgs e) => SelectedAnnotation = e.ClickedItem as BaseAnnotation;
}

AnnotationsListViewModel.cs

class AnnotationsListViewModel : ViewModalBase
{
    private ICollectionView annotationsList = null;

    public ICollectionView AnnotationsList
    {
        get { return annotationsList; }
        set { if(value != annotationsList) { annotationsList = value; OnPropertyChanged(nameof(AnnotationsList)); } }
    }
}

用这样的用户控件替换了 ListView Renderer.cs

<local:AnnotationsList x:Name="ctrl_AnnotationsList" Margin="0,12,0,0" Grid.Row="1" VerticalAlignment="Stretch" Visibility="{Binding IsAnnotationsListOpen, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />

在父控件类Renderer.cs(模板控件)中,AnnotationsList当第一次渲染父控件并绑定PropertyChanged事件时,会像这样获得对控件的引用。

AnnotationsList = GetTemplateChild("ctrl_AnnotationsList") as AnnotationsList;
AnnotationsList.PropertyChanged -= null;
AnnotationsList.PropertyChanged += OnAnnotationsListPropertyChanged;

添加了以下代码以触发AnnotationsList控件中的属性更改。

private void OnAnnotationsListPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    switch(e.PropertyName)
    {
        case "SelectedAnnotation":
            var annotation = (sender as AnnotationsList).SelectedAnnotation;
            if (annotation != null)
                GoToAnnotation(annotation).GetAwaiter();

            break;
        default:
            break;
    }
}

现在它被配置为ItemClick触发ListViewItems.

希望这对可能正在寻找类似解决方案的人有所帮助。

于 2021-08-11T16:53:46.250 回答
0

我的猜测是我必须将命令绑定到按钮。但我也找不到这样做的方法。

更好的方法是使用命令来接近,我将在下面分享您可以参考的详细步骤。请注意,您需要将当前页面数据上下文设置为 this this.DataContext = this;。它可以确保您可以从后面的代码中访问命令DataTemplate

Xaml 代码

<Grid>
    <ListView x:Name="MyListView" ItemsSource="{x:Bind Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding Header}" />
                        <TextBlock
                            Margin="20,0,0,10"
                            FontSize="12"
                            Text="{Binding DisplayTitle}"
                            TextWrapping="WrapWholeWords"
                            Visibility="Visible" />
                    </StackPanel>
                    <CommandBar Grid.Column="1">
                        <CommandBar.SecondaryCommands>
                            <AppBarElementContainer>
                                <StackPanel Orientation="Horizontal">
                                    <Button
                                        x:Name="btn_RemoveFromList"
                                        Command="{Binding DataContext.DeleteCommand, ElementName=MyListView}"
                                        CommandParameter="{Binding}">
                                        <Button.Content>
                                            <SymbolIcon Symbol="Delete" />
                                        </Button.Content>
                                        <ToolTipService.ToolTip>
                                            <ToolTip Content="Delete" Placement="Mouse" />
                                        </ToolTipService.ToolTip>
                                    </Button>
                                </StackPanel>
                            </AppBarElementContainer>
                        </CommandBar.SecondaryCommands>
                    </CommandBar>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

背后的代码

public sealed partial class ListPage : Page
{
    public ListPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }
    private ObservableCollection<Model> Items { set; get; }
   
    public ICommand DeleteCommand
    {
        get
        {
            return new CommadEventHandler<Model>((s) =>
            {
                Items.Remove(s);

            });
        }
    }
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        MakeDataSource();
    }
    private void MakeDataSource()
    {
        Items = new ObservableCollection<Model>();
        for (int i = 0; i < 10; i++)
        {
            Items.Add(new Model()
            {
                Header = $"header{i}",
                DisplayTitle= $"DisplayTitle{i}"
            });
        }
     
    }
}
public class Model
{
    public string Header { get; set; }
    public string DisplayTitle { get; set; }
}

class CommadEventHandler<T> : ICommand
{
    public event EventHandler CanExecuteChanged;

    public Action<T> action;
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        this.action((T)parameter);
    }
    public CommadEventHandler(Action<T> action)
    {
        this.action = action;

    }
}
于 2021-08-05T02:43:07.030 回答