【问题标题】:Xamarin.forms how to get ID from image button?Xamarin.forms 如何从图像按钮获取 ID?
【发布时间】:2020-05-20 16:23:46
【问题描述】:

Xamarin.forms 如何从图像按钮获取 ID?

<ImageButton x:Name="quizButton" Source="quiz2.png"  Clicked="OnQuizClicked" />

我试过这种方式,但他给我一个错误:System.NullReferenceException: 'Object reference not set to an instance of an object.'

private async void OnQuizClicked(object sender, EventArgs e)
    {
         var button = sender as Button;
         var route = button?.BindingContext as Routes;

        var token = Application.Current.Properties["MyToken"].ToString();
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        var response = await client.GetStringAsync("URL");
        List<Question> punkty = JsonConvert.DeserializeObject<List<Question>>(response);
        List<Question> list = new List<Question>();
        foreach (Question tmp in punkty)
        {
            if (tmp.RouteId == route.Id)
            {
                list.Add(tmp);
            }
        }


        await Navigation.PushAsync(new UserQuestionPage());
    }

【问题讨论】:

  • 您将sender 转换为Button,而不是ImageButton
  • 能否请您标记正确的答案,以便我们可以帮助更多有相同问题的人:)。
  • 好的,没问题:)

标签: xaml xamarin xamarin.forms


【解决方案1】:

ButtonImagebutton 是 Xamarin.forms 中的两个不同控件。

您在 Xaml 中定义了一个 ImageButton,那么 Clicked Event 中的 sender 应该是 ImageButton

private async void OnQuizClicked(object sender, EventArgs e)
{
    var imgButton = sender as ImageButton;

    //...
}

【讨论】:

    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2018-06-02
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多