我最近一直在为Xamarin.Forms尝试Prism框架,而且我遇到了EventToCommandBehavior的一个问题,我很确定它应该有效。
当我尝试使用NavigationParameters()将对象从ListView发送到新视图时,它会自动生成为字符串而不是之前发送的对象。
当我尝试将其强制转换为对象时,会出现InvalidCastException。
ListView.cs我通过Navigate()发送数据到新视图:
private ObservableCollection<Employee> _employeeList = new ObservableCollection<Employee>();
_employeeList.Add("employee", new Employee{ Id = 1, FirstName = "FirstTest", LastName = "LastTest" });
private async void Navigate()
{
var employeePara = new NavigationParameters();
employeePara.Add("employee", _selectedEmployee);
await _navigationService.NavigateAsync("EmployeeDetail" + employeePara);
}
新视图,我尝试将数据作为对象:
private Employee _employee;
public void OnNavigatingTo(NavigationParameters parameters)
{
try
{
if (parameters.ContainsKey("employee"))
_employee = (Employee)parameters["employee"]; // invalid cast happening here
EmployeeFullName = _employee.FirstName;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
XAML:
<ContentPage.Resources>
<ResourceDictionary>
<c:ItemTappedEventArgsConverter x:Key="itemTappedEventArgs" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<ListView ItemsSource="{Binding EmployeeList}" SelectedItem="{Binding SelectedEmployee}">
<ListView.Behaviors>
<b:EventToCommandBehavior
EventName="ItemTapped"
Command="{Binding EmployeeTappedCommand}"/>
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding FullName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
答案 0 :(得分:0)
Prism for Forms示例也使用类似的方案,但具有不同的NavigateAsync方法签名。 我的猜测,你的错了吗?
示例代码await _navigationService.NavigateAsync("RecipePage", p);