警报框未出现在xamarin表单中,DisplayAlert()

时间:2016-12-08 20:57:48

标签: c# xaml xamarin xamarin.forms

我在点击或点击所选的ListView框后尝试显示警告框。目前selectedItem绑定到SelectedTicket,它在ViewModel中触发对象调用SelectedTicket。触发SelectedTicket后,它会使用popup.show()方法执行DisplayAlert()方法。 DisplayAlert()方法执行但不显示AlertBox。

Image

============================================== < / p>

//// Xaml Page

<ListView ItemsSource="{Binding TicketList,Mode=OneWay}" RowHeight="130"
     ItemTemplate="{StaticResource TicketListTileTemplate}"  BackgroundColor="#d9deeb"
     SelectedItem="{Binding SelectedTicket, Mode=TwoWay}" SeparatorVisibility="None">
</ListView>

=============================================== ===

//// ViewModal

public object SelectedTicket
{
    get
    {
        return _SelectedTicket;
    }
    set
    {
        if (SetProperty(ref _SelectedTicket, value))
        {
            if ((value != null) && (value is TicketListItem))
            {
                popup1.Show();
                SelectedTicket = null;
            }
        }
    }
}

=============================================== =======

//// Popup.cs

async public void Show()
{
    DisplayAlert("Alert", "Your have been alerted", "OK");
}

2 个答案:

答案 0 :(得分:6)

我没有看到DisplayAlert的最常见原因之一是因为它是在屏幕上未激活的页面上调用的。

作为快速解决方法/测试,您可以

await Application.Current.MainPage.DisplayAlert("Alert", "Your have been alerted", "OK");

如果这样可行,我的第一个假设就得到了确认。

我总是试图让我的代码保持干净,因此从ViewModel调用肯定是一个很好的方法。通常,您的MVVM库有一些代码可以帮助显示警报。

答案 1 :(得分:1)

Page仅适用于ContentPage个对象(例如NavigationPagePage),请参阅here,您的Popup.cs可能不是DisplayAlert 1}}对象。此外,您还没有等待Show()您总是想要使用异步方法。最后,您的<ListView ItemsSource="{Binding TicketList,Mode=OneWay}" RowHeight="130" ItemTemplate="{StaticResource TicketListTileTemplate}" BackgroundColor="#d9deeb" SelectedItem="{Binding SelectedTicket, Mode=TwoWay}" SeparatorVisibility="None" ItemSelected="OnItemTapped"> <!-- Notice ItemTapped here will trigger when an item is tapped, imagine that --> 方法可能没有在UI线程上运行。

为什么不尝试显示来自您的XAML页面的代码隐藏的警报,而不是尝试显示来自ViewModel的警报:

XAML:

....

private TicketViewModel _viewModel = new TicketViewModel();

....

public async void OnItemTapped (object o, ItemTappedEventArgs e) { //Notice I added 'async' to the method here, that is so we can 'await' the DisplayAlert below (ALWAYS 'await' the DisplayAlert and ANY other async methods)
    TicketListItem item = (TicketListItem)o;

    if (item != null) {
        await DisplayAlert("Alert", "Your have been alerted", "OK"); //Notice the 'await' here
        _viewModel.SelectedTicket = null;
    }
}

在代码隐藏中:

public class EmployeeRate : BaseEntity
{
    [Key]
    public int EmployeeRateId { get; set; }

    public int EmployeeId { get; set; }

    public double Rate { get; set; }
}

public class BaseEntity
{
    public bool ActiveFlag { get; set; }

    public DateTime CreateStamp { get; set; }

    public DateTime UpdateStamp { get; set; }

    public string LastModifiedBy { get; set; }
}