【问题标题】:Pass Model to ViewModel on button click Xamarin MVVM将模型传递给 ViewModel 按钮单击 Xamarin MVVM
【发布时间】:2020-11-17 08:17:31
【问题描述】:

我正在使用 Xamarin (MVVM),并且我有一个显示来自 UserSelectionList(model) 的数据的按钮

XAML:

<Button x:Name="userOne" 
                                            CommandParameter="{x:Reference userOne}"
                                            Text="{Binding UserSelectionList[0].Abbreviation}" 
                                            Command="{Binding ButtonSelectedCommand}"
                                            TextColor="White" 
                                            HorizontalOptions="Center" 
                                            VerticalOptions="Center" 
                                            BorderWidth="1"
                                            FontSize="92"
                                            HeightRequest="320"
                                            WidthRequest="320"
                                            Grid.Row="1"
                                            Grid.Column="0"
                                        />

UserSelectionViewModel型号

public class UserSelectionViewModel
    {
        public string UserName { get; set; }
        public string Abbreviation { get; set; }
    }

如您所见,我有一个使用双向绑定的 Command 属性,所以在我的视图模型中我有类似的内容:

 //Initialize viewmodel

   public UserSelectionPageViewModel()
    {
        _ = LoadItems();

    }


//Create an UserSelectionViewModel instance


   private ObservableCollection <UserSelectionViewModel> _userSelectionList = new ObservableCollection<UserSelectionViewModel>();

    public ObservableCollection<UserSelectionViewModel> UserSelectionList
    {
        get { return _userSelectionList; }
        set { SetProperty(ref _userSelectionList, value, nameof(UserSelectionList)); }
    }




public ICommand ButtonSelectedCommand
    {
        get { return new Command(async x => await SelectedButton(x as Button)); }
    }




 // Fill UserSelectionList

private async Task LoadItems()
        {
            try

            {
              
                var userList = await UserHelper.LoadUsers();
               
                UserSelectionList = new ObservableCollection<UserSelectionViewModel>(userList);
            }
            catch (Exception ex)
            {
                return;
            }
        }

 //Assign UserSelectionViewModel to UserSelectionList

    private async Task<bool> SelectedButton(Button button)
    {
        var a = "";
        return true;
    }

我的问题是:如何绑定我的 UserSelectionList[0] 并在我的 ViewModel SelectedButton 方法中访问该模型?问候

【问题讨论】:

  • 这段代码打破了我的大脑。 UserSelectionList 是什么?收藏?在Button 之外是否有一些ItemsControlListBox?为什么async 方法里面没有await?当前代码不起作用吗?编译错误?例外?什么都没发生?将 Button 传递给 CommandParameter 会破坏 MVVM,因为您不能将任何 View 项传递给 ViewModel,但为什么需要它?请用更多代码和更多详细信息填写问题。
  • 你为什么不直接做CommandParameter="{Binding UserSelectionList[0]}"
  • 我应该如何在 ViewModel 中接收? @杰森
  • 使用Command&lt;T&gt;传递T类型的参数

标签: c# xamarin mvvm


【解决方案1】:

你可以定义UserSelectionViewModel如下:

public class UserSelectionViewModel
{
    public string UserName { get; set; }
    public string Abbreviation { get; set; }

    public ICommand ButtonSelectedCommand
    {
        get
        {
            return new Command((e) =>
            {
                var item = (e as UserSelectionViewModel);
                // logic on item
                Console.WriteLine(item.UserName);
            });
        }
    }
}

然后创建ViewModel来设置一些特殊的数据:

public class ViewModel
{
    public ObservableCollection<UserSelectionViewModel> UserSelectionList { set; get; }

    public ViewModel()
    {
        UserSelectionList = new ObservableCollection<UserSelectionViewModel>();
        UserSelectionList.Add(new UserSelectionViewModel() { UserName = "1", Abbreviation = "button one" });
        UserSelectionList.Add(new UserSelectionViewModel() { UserName = "2", Abbreviation = "button two" });
        UserSelectionList.Add(new UserSelectionViewModel() { UserName = "3", Abbreviation = "button three" });
        UserSelectionList.Add(new UserSelectionViewModel() { UserName = "4", Abbreviation = "button four" });
        UserSelectionList.Add(new UserSelectionViewModel() { UserName = "5", Abbreviation = "button five" });
        UserSelectionList.Add(new UserSelectionViewModel() { UserName = "6", Abbreviation = "button six" });

    }
}

现在Xaml代码也需要稍微修改一下:

<Button Text="{Binding UserSelectionList[0].Abbreviation}"
        Command="{Binding UserSelectionList[0].ButtonSelectedCommand}"
        CommandParameter="{Binding UserSelectionList[0]}"/>

那么当点击按钮时会收到每个UserSelectionViewModel的数据。

输出:

07-28 10:34:24.307 I/mono-stdout(12600): 1
07-28 10:34:25.483 I/mono-stdout(12600): 1
07-28 10:34:26.452 I/mono-stdout(12600): 1

另外,如果ButtonListView里面,也可以得到UserSelectionViewModel。示例代码如下:

<ListView  x:Name="listView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout BackgroundColor="#eee" x:Name="Item"
                             Orientation="Vertical">
                    <StackLayout Orientation="Horizontal">
                        <Label Text="{Binding UserName}"
                               TextColor="#f35e20" />
                        <Label Text="{Binding Abbreviation}"
                               HorizontalOptions="EndAndExpand"
                               TextColor="#503026" />
                        <Button Text="{Binding Abbreviation}"
                                Command="{Binding ButtonSelectedCommand}"
                                CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}" />
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2020-01-27
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多