【发布时间】: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之外是否有一些ItemsControl或ListBox?为什么async方法里面没有await?当前代码不起作用吗?编译错误?例外?什么都没发生?将Button传递给CommandParameter会破坏 MVVM,因为您不能将任何 View 项传递给 ViewModel,但为什么需要它?请用更多代码和更多详细信息填写问题。 -
你为什么不直接做
CommandParameter="{Binding UserSelectionList[0]}" -
我应该如何在 ViewModel 中接收? @杰森
-
使用
Command<T>传递T类型的参数