【发布时间】:2019-10-04 22:24:24
【问题描述】:
我在Cell 中有ListView 和Button。当我单击单元格的按钮时,我想获取当前项目。
这是列表视图
<ListView x:Name="list1" ItemsSource="{Binding StudentList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Image x:Name="Image1" Source="other.png" />
<Label TextColor="{StaticResource mainColor}"
Text="{Binding StudentName}" />
<Button x:Name="mybtn"
BindingContext="{Binding Source={x:Reference list1}, Path=BindingContext}"
BackgroundColor="{DynamicResource CaribGreenPresent}"
Text="{Binding AttendanceTypeStatusIdGet, Converter={x:StaticResource IDToStringConverter}}">
</Button>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
当我点击mybtn我想在 ViewModel 中获取当前项目时,我该怎么做?
这是我的 ViewModel 代码
private List<Student> _studentList;
public List<Student> StudentList
{
get { return _studentList; }
set { SetProperty(ref _studentList, value); }
}
列表截图:
编辑 1: 在 ViewModel 中出现错误:
参数 1:无法从“方法组”转换为“操作”
这是代码
//Constructor
public StudentAttendanceListPageViewModel(INavigationService _navigationService):base(_navigationService)
{
ItemCommand=new DelegateCommand<Student>(BtnClicked);
}
public DelegateCommand<Student> ItemCommand { get; }
public void BtnClicked(object sender, EventArgs args)
{
var btn = (Button)sender;
var item = (Student)btn.CommandParameter;
// now item points to the Student selected from the list
}
按钮 XAML
<Button x:Name="mybtn"
BindingContext="{Binding Source={x:Reference list1}, Path=BindingContext}"
Command="{Binding ItemCommand }"
CommandParameter="{Binding Source={x:Reference mybtn}}"
Text="{Binding AttendanceTypeStatusId, Converter={x:StaticResource IDToStringConverter}}">
</Button>
错误截图:
【问题讨论】:
-
为什么不把命令放在学生的视图模型上?
-
ItemCommand仅在 StudentViewModel 内。 -
那么为什么不直接使用
this来获得点击的StudentViewModel? -
@Haukinger - 很抱歉,我完全不理解。您能否将其写为答案或解释更多。谢谢。
标签: xamarin mvvm xamarin.forms prism