【问题标题】:Xamarin Forms Binding Command from View Model to Button in List View Data TemplateXamarin 表单从视图模型绑定命令到列表视图数据模板中的按钮
【发布时间】:2018-04-19 19:04:04
【问题描述】:

我正在使用 Xamarin.Forms 2.4 构建社交帖子共享应用程序,它与我的 API 对话。

我有 PostsPage,它使用 PostDataViewModel 将 ObservableCollection 加载到 PostsPage 中定义的 ListView。列表视图的数据模板指向视图文件。但是,在 Post View Template 中,我可以绑定到 My Post Model 的各个属性,但绑定到 ViewModel 上存在的命令不起作用。我试过 x:Reference 没有运气。

我的模特:

using System;
using System.Collections.Generic;

namespace SOD_APP_V2.Model
{
public class PostDataModel
{
    public string ID { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public string Image { get; set; }
    public string SocialMedia { get; set; }
    public string AvailableTime { get; set; }
    public string Audiences { get; set; }
    public string Topics { get; set; }
    public List<PostVersion> Versions { get; set; }

    public PostDataModel PostDetails
    {
        get
        {
            return this;
        }
    }
}
public class PostVersion
{
    public string SocialMediaID { get; set; }
    public string IconPath { get; set; }
    public int CharacterCount { get; set; }
    public string Message { get; set; }
}
}

我的视图模型:

namespace SOD_APP_V2.ViewModel
{
public class PostDataViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    //Bindable properties
    public ObservableCollection<PostDataModel> PostDataCollection { get; set; }
    public ICommand LoadMorePostsCommand { get; private set; }
    public ICommand RejectPostCommand { get; private set; }

    public static JObject SocialmediaSites { get; set; }
    public object SelectedItem { get; set; }

    bool isLoadMoreEnabled;
    public bool IsLoadMoreEnabled
    {
        get
        {
            return isLoadMoreEnabled;
        }
        set
        {
            if (isLoadMoreEnabled != value)
            {
                isLoadMoreEnabled = value;
                OnPropertyChanged((nameof(IsLoadMoreEnabled)));
            }
        }
    }

    string pageTitle;
    public string PageTitle
    {
        get
        {
            return pageTitle;
        }
        set
        {
            if (pageTitle != value)
            {
                pageTitle = value;
                OnPropertyChanged(nameof(PageTitle));
            }
        }
    }

    int currentPage = 1;
    public int CurrentPage
    {
        get
        {
            return currentPage; 
        }
        set
        {
            if(currentPage != value)
            {
                currentPage = value;
                OnPropertyChanged(nameof(CurrentPage));
            }
        }
    }

    public PostDataViewModel()
    {
        PostDataCollection = new ObservableCollection<PostDataModel>();
        SocialmediaSites = default(JObject);

        IsLoadMoreEnabled = true;
        LoadMorePostsCommand =
            new Command(async () => await GetPosts(), () => IsLoadMoreEnabled);

        RejectPostCommand = new Command<PostDataModel>((post) =>
        {
            System.Diagnostics.Debug.WriteLine("Reject command executed");
            System.Diagnostics.Debug.WriteLine("Post ID: " + post.ID);
        });

        string deployment = ConfigController.GetDeploymentName(ApiController.DeploymentDomain);

        MessagingCenter.Subscribe<PostsPage, JArray>(this, "translations", (sender, arg) => {
            PageTitle = (arg[0].ToString() != "") ? arg[0].ToString() : "Posts from " + deployment;
        });
        if (deployment != null)
        {
            //TODO: lang packs
            PageTitle = "Posts from " + deployment;
        }
    }

    public async Task<bool> GetPosts()
    {
        ...
    }

    protected virtual void OnPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(nameof(propertyName)));
        }
    }
}

}

我的帖子页面 XAML:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SOD_APP_V2"
xmlns:view="clr-namespace:SOD_APP_V2.View;assembly=SOD_APP_V2"
xmlns:viewModel="clr-namespace:SOD_APP_V2.ViewModel;assembly=SOD_APP_V2"
xmlns:controls="clr-namespace:SOD_APP_V2.Controls;assembly=SOD_APP_V2"
x:Class="SOD_APP_V2.PostsPage" x:Name="PostsPage"
>
<ContentPage.BindingContext>
    <viewModel:PostDataViewModel/>
</ContentPage.BindingContext>
<ContentPage.Content>
    <StackLayout>
        <StackLayout Orientation="Vertical" Padding="10, 5, 10, 5">
            <Label x:Name="titleLabel" Text="{Binding PageTitle}"
                     VerticalOptions="Start"
                     HorizontalTextAlignment="Center"
                     VerticalTextAlignment="Center"
                     BackgroundColor="Transparent"
                     HorizontalOptions="CenterAndExpand" />
            <controls:InfiniteListView x:Name="listView"
                        SelectedItem="{Binding SelectedItem,Mode=TwoWay}"
                        IsLoadMoreItemsPossible="{Binding IsLoadMoreEnabled}"
                        LoadMoreInfiniteScrollCommand="{Binding LoadMorePostsCommand}"
                        IsEnabled="true"
                        IsBusy="{Binding IsBusy}"
                        HasUnevenRows="true"
                        ItemsSource="{Binding PostDataCollection}"
                        SeparatorVisibility="None">
                <controls:InfiniteListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <view:PostViewTemplate/>
                        </ViewCell>
                    </DataTemplate>
                </controls:InfiniteListView.ItemTemplate>
            </controls:InfiniteListView>
        </StackLayout>
        <StackLayout HorizontalOptions="FillAndExpand"
            VerticalOptions="End">
            <Label x:Name="infoLabel" Text="test"
                    Opacity="0"
                    TextColor="White"
                    BackgroundColor="#337ab7"
                    HorizontalTextAlignment="Center">
                </Label>
        </StackLayout>
    </StackLayout>
</ContentPage.Content>

最后是描述每个帖子的帖子视图模板:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:model="clr-namespace:SOD_APP_V2.Model;assembly=SOD_APP_V2"
xmlns:controls="clr-namespace:SOD_APP_V2.Controls;assembly=SOD_APP_V2"
x:Class="SOD_APP_V2.View.PostViewTemplate">
<ContentView.Resources>
    <ResourceDictionary>
        <Style TargetType="controls:AwesomeButton">
            <Setter Property="BorderWidth" Value="1"/>
            <Setter Property="TextColor" Value="White"/>
            <Setter Property="BorderRadius" Value="7"/>
            <Setter Property="FontFamily" Value="FontAwesome"/>
        </Style>
    </ResourceDictionary>
</ContentView.Resources>
<ContentView.Content>
    <Frame HasShadow="false" CornerRadius="5" IsClippedToBounds="true" OutlineColor="#09478e" Padding="0" Margin="10">
    <Grid 
        Padding="0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1" />
            <ColumnDefinition Width="1" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="1" />
            <ColumnDefinition Width="1" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="1"></RowDefinition>
            <RowDefinition Height="100"></RowDefinition>
            <RowDefinition Height="1"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
            <RowDefinition Height="1"></RowDefinition>
        </Grid.RowDefinitions>
        <StackLayout Orientation="Horizontal" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="6" BackgroundColor="#B0C4DB" Padding="5">
            <Label x:Name="postTitle" Text="{Binding Title}" TextColor="#09478e" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
            <StackLayout Orientation="Horizontal" VerticalOptions="CenterAndExpand" HorizontalOptions="End">
            <controls:AwesomeButton Clicked="OnAvailableTimePopupClicked" CommandParameter="{Binding AvailableTime}" Text="&#xf017;" TextColor="#09478e" BorderWidth="0" Margin="-5" BackgroundColor="Transparent" WidthRequest="36" FontSize="24"></controls:AwesomeButton>
            <controls:AwesomeButton Clicked="OnAudiencesPopupClicked" CommandParameter="{Binding Audiences}" Text="&#xf0c0;" TextColor="#09478e" BorderWidth="0" Margin="-5" BackgroundColor="Transparent" WidthRequest="36" FontSize="24"></controls:AwesomeButton>
            <controls:AwesomeButton Clicked="OnTopicsPopupClicked" CommandParameter="{Binding Topics}" Text="&#xf02c;" TextColor="#09478e" BorderWidth="0" Margin="-5" BackgroundColor="Transparent" WidthRequest="36" FontSize="24"></controls:AwesomeButton>
            </StackLayout>
        </StackLayout>
        <controls:RepeaterView  Grid.Row="1" Grid.Column="2"
                              ItemsSource="{Binding Versions}"
                              NoOfColumns="3"
                              >
            <controls:RepeaterView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Spacing="0" >
                        <Label Text="{Binding Message}" IsVisible="false"/>
                        <Image Source="{Binding IconPath}">
                            <Image.GestureRecognizers>
                                <TapGestureRecognizer
                                        Tapped="OnMessageVersionClicked"
                                        NumberOfTapsRequired="1" />
                            </Image.GestureRecognizers>
                        </Image>
                    </StackLayout>
                </DataTemplate>
            </controls:RepeaterView.ItemTemplate>
        </controls:RepeaterView>

        <Image BackgroundColor="White" Grid.Row="3" Grid.Column="2" Source="{Binding Image}" VerticalOptions="FillAndExpand"/>
        <Label x:Name="postMessage" BackgroundColor="White" Grid.Row="3" Grid.Column="3" Text="{Binding Message}" TextColor="#09478e" VerticalOptions="FillAndExpand" />

        <controls:AwesomeButton Clicked="OnSharePostClicked" CommandParameter="{Binding ID}" BackgroundColor="#5cb85c" Grid.Row="5" Grid.Column="2" Text="&#xf1e0; Share" BorderColor="#5cb85c"></controls:AwesomeButton>
        <controls:AwesomeButton Clicked="OnSchedulePostClicked" CommandParameter="{Binding ID}" BackgroundColor="#5bc0de" Grid.Row="5" Grid.Column="3" Text="&#xf073; Schedule" BorderColor="#5bc0de"></controls:AwesomeButton>

        <controls:AwesomeButton Clicked="OnEditPostClicked" CommandParameter="{Binding PostDetails}" TextColor="#09478e" BackgroundColor="White" Grid.Row="6" Grid.Column="2" Text="&#xf040; Edit" BorderColor="#09478e"></controls:AwesomeButton>
        <controls:AwesomeButton  Command="{Binding Path=DataContext.RejectPostCommand}" CommandParameter="{Binding}" BackgroundColor="#d9534f" Grid.Row="6" Grid.Column="3" Text="&#xf00d; Reject" BorderColor="#d9534f"></controls:AwesomeButton>
        <!-- Inner Border -->
        <BoxView Grid.Row="2" Grid.RowSpan="3" Grid.Column="1" BackgroundColor="#09478e"></BoxView>
        <BoxView Grid.Row="2" Grid.RowSpan="3" Grid.Column="4" BackgroundColor="#09478e"></BoxView>
        <BoxView Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="2" BackgroundColor="#09478e"></BoxView>
        <BoxView Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="4" BackgroundColor="#09478e"></BoxView>
    </Grid>
    </Frame>
</ContentView.Content>

正如您在 Post View Template 中看到的,我试图在 ViewModel 中绑定 RejectPostCommand,但它没有绑定。我尝试了 x:Reference to PostsPage,但它抛出了异常,因为它无法从我的视图模板中找到该页面。我需要能够以某种方式访问​​命令。有人有什么想法吗?

【问题讨论】:

  • 我发现这篇文章很有帮助techsolutions2017.blogspot.it/2017/01/…
  • 我找到的唯一可行的解​​决方案是将视图模板包含在与 PostsPage 相同的 XAML 文件中,当 x:reference 正在工作并且命令正在触发时。但是有什么方法可以保持视图分离?
  • 试试这个命令="{Binding Source={x:Reference listView}, Path=BindingContext.RejectPostCommand}"
  • @ZiyadGodil 我试过这个,但我得到一个异常,说找不到名称。所以它无法从模板内部找到 listView。为了解决这个问题,我将查看模板移到了帖子页面。

标签: xamarin mvvm data-binding xamarin.forms xamarin.forms.listview


【解决方案1】:

一种解决方案是将 ICommand 属性添加到您的模型,然后在您的 viewModel 中,在将帖子添加到 PostDataCollection 之前,将新 ICommand 属性的值设置为 viewmodel 的期望命令。比如:

public async Task<bool> GetPosts()
{
    var response = await FetchPostsFromApi(); 
    foreach(var post in response.posts)
    {
        post.NewCommand = RejectPostCommand;
        PostDataCollection.Add(post)
    }
    return response.HasMoreItems;
}

现在在您的帖子视图模板中绑定模型的新 ICommand 属性。

【讨论】:

  • 感谢您的解决方案!我解决了我的问题,我将帖子页面中的 PostViewTemplate 代码和事件处理程序也移动到帖子页面。现在我查看模型的命令确实有效,而且我使用的文件更少!
【解决方案2】:

所以问题与在 ViewModel 中的 PostViewTemplate 中设置绑定有关。我无法引用 listView 或 PostsPage 作为绑定源,因为它在另一个文件中,我无法绕过它。我通过将 PostViewTemplate XAML 移动到 PostsPage 解决了这个问题。所以现在我可以使用

{Binding Path=BindingContext.RejectPostCommand, Source={x:Reference listView}}

它有效!

【讨论】:

    【解决方案3】:

    您可以在 PostViewTemplate 中创建命令,然后将其绑定到 ListView。示例如下:

    PostViewTemplate.xaml.cs:

    public partial class PostViewTemplate : ContentView
    {
        public static BindableProperty RejectPostCommandProperty = BindableProperty.Create(
            nameof(RejectPostCommand),
            typeof(ICommand),
            typeof(PostViewTemplate),
            default(ICommand),
            defaultBindingMode: BindingMode.OneWay);
    
        public ICommand RejectPostCommand
        {
            get { return (ICommand)GetValue(RejectPostCommandProperty); }
            set { SetValue(RejectPostCommandProperty, value); }
        }
    }
    

    在 PostViewTemplate.xaml 中

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentView xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        x:Name="PostViewTemplate"
        xmlns:model="clr-namespace:SOD_APP_V2.Model;assembly=SOD_APP_V2"
        xmlns:controls="clr-namespace:SOD_APP_V2.Controls;assembly=SOD_APP_V2"
        x:Class="SOD_APP_V2.View.PostViewTemplate">
    <ContentView.Content>
        ....
        <controls:AwesomeButton  Command="{Binding RejectPostCommand, Source={x:Reference PostViewTemplate}}" CommandParameter="{Binding}" BackgroundColor="#d9534f" Grid.Row="6" Grid.Column="3" Text="&#xf00d; Reject" BorderColor="#d9534f"></controls:AwesomeButton>
        ....
    </ContentView.Content>
    </ContentView>
    

    注意我在 PostViewTemplate.xaml 中设置了 ContentView 的名称

    现在您只需像这样在 ContentPage 中绑定这个新命令。

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:SOD_APP_V2"
        xmlns:view="clr-namespace:SOD_APP_V2.View;assembly=SOD_APP_V2"
        xmlns:viewModel="clr-namespace:SOD_APP_V2.ViewModel;assembly=SOD_APP_V2"
        xmlns:controls="clr-namespace:SOD_APP_V2.Controls;assembly=SOD_APP_V2"
        x:Class="SOD_APP_V2.PostsPage" x:Name="PostsPage">
        <ContentPage.BindingContext>
            <viewModel:PostDataViewModel/>
        </ContentPage.BindingContext>
        <ContentPage.Content>
            ....
            <controls:InfiniteListView x:Name="listView"
                    SelectedItem="{Binding SelectedItem,Mode=TwoWay}"
                    IsLoadMoreItemsPossible="{Binding IsLoadMoreEnabled}"
                    LoadMoreInfiniteScrollCommand="{Binding LoadMorePostsCommand}"
                    IsEnabled="true"
                    IsBusy="{Binding IsBusy}"
                    HasUnevenRows="true"
                    ItemsSource="{Binding PostDataCollection}"
                    SeparatorVisibility="None">
                <controls:InfiniteListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <view:PostViewTemplate RejectPostCommand="{Binding BindingContext.RejectPostCommand, Source={x:Reference listView}}"/>
                        </ViewCell>
                    </DataTemplate>
                </controls:InfiniteListView.ItemTemplate>
            </controls:InfiniteListView>
            ....
        </ContentPage.Content>
    </ContentPage>
    

    【讨论】:

      【解决方案4】:

      将 PostViewTemplate XAML 移动到 PostsPage 可能有效,但现在您没有可重复使用的模板。

      您可以通过对原始代码进行以下 3 项小改动来创建可重复使用的解决方案。

      向 PostViewTemplate 代码隐藏添加可绑定属性,如下所示:

          public static BindableProperty ParentBindingContextProperty = 
              BindableProperty.Create(nameof(ParentBindingContext), typeof(object), 
              typeof(PostViewTemplate), null);
      
          public object ParentBindingContext
          {
              get { return GetValue(ParentBindingContextProperty); }
              set { SetValue(ParentBindingContextProperty, value); }
          }
      

      将该属性绑定到 PostsPage XAML 中的 ViewModel,如下所示:

      <view:PostViewTemplate ParentBindingContext="{Binding Source={x:Reference Home}, Path=BindingContext}"/>
      

      现在您可以直接从 PostViewTemplate 中的绑定访问您的“父”视图模型,就像这样(注意,您需要向 ContentView 添加一个 x:Name 以用作您的绑定):

      <ContentView ... x:Name="PostView" ...>
      
      <controls:AwesomeButton BindingContext="{Binding Source={x:Reference PostView}, Path=ParentBindingContext}" Command="{Binding OnTopicsPopupClicked}" CommandParameter="{Binding Topics}" Text="&#xf02c;" TextColor="#09478e" BorderWidth="0" Margin="-5" BackgroundColor="Transparent" WidthRequest="36" FontSize="24"></controls:AwesomeButton>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-10
        • 2022-10-18
        • 2012-10-02
        • 2013-04-05
        相关资源
        最近更新 更多