web-dev-qa-db-fra.com

Liaison de commande Impossible de transtyper un objet de type 'System.Reflection.RuntimeEventInfo' en type 'System.Reflection.MethodInfo'

Lorsque je connecte mon bouton à une commande via XAML, j'obtiens une erreur d'exécution System.Windows.Markup.XamlParseException: fournir une valeur sur 'System.Windows.Data.Binding' a levé une exception. ---> System.InvalidCastException: impossible de convertir un objet de type 'System.Reflection.RuntimeEventInfo' en type 'System.Reflection.MethodInfo'.

Lorsque je supprime la liaison de commande en XAML, tout fonctionne bien et mes éléments s'affichent, etc. Voici la liaison de commande:

Click="{Binding ElementName=MainGrid, Path=DataContext.AlertClickCommand}"

Code pour câbler le modèle de vue (dans le code derrière ma fenêtre):

this.AlertsView.DataContext = GlobalStuff.AlertManager1.AlertViewModel1;

Voici mon modèle de vue Mon modèle de vue est le contexte de données de ma vue

using System.Collections.Generic;
using System.ComponentModel;
using Arkle.SharedUI.Model;
using Arkle.SharedUI.ViewModel.Commands;

namespace Arkle.SharedUI.ViewModel
{
    public class AlertViewModel : INotifyPropertyChanged
    {

        private List<Alert> _alerts = new List<Alert>();
        public List<Alert> Alerts
        {
            get { return _alerts; }
            set
            {
                _alerts = value;
                OnPropertyChanged("Alerts");
            }
        }


        public AlertViewModel()
        {
            if (DesignerProperties.IsInDesignMode)
            {
                LoadDesignTimeData();
            }
        }

        private void LoadDesignTimeData()
        {
            Alerts.Add(new Alert { BackgroundMessage = "Sis", IsAlerting = true, OverlayMessage = "3 mins", Tip = "Sis Data not received for 3 mins" });
            Alerts.Add(new Alert { BackgroundMessage = "Bets", IsAlerting = true, OverlayMessage = "4", Tip = "4 unchecked danger bets" });
            Alerts.Add(new Alert { BackgroundMessage = "Texts", IsAlerting = false, OverlayMessage = "3", Tip = "3 Unchecked Text Bets" });
        }

        private AlertClickCommand _alertClickCommand;
        public AlertClickCommand AlertClickCommand
        {
            get { return _alertClickCommand ?? (_alertClickCommand = new AlertClickCommand(this)); }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Voici mon xaml

<UserControl x:Class="Arkle.SharedUI.View.AlertsView"
    xmlns="http://schemas.Microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.Microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.Microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:viewModel="clr-namespace:Arkle.SharedUI.ViewModel"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance Type=viewModel:AlertViewModel, IsDesignTimeCreatable=True}"
        x:Name="EarlyPriceEditorViewModelWindow"
    Height="Auto" Width="Auto">
    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </UserControl.Resources>

    <Grid Name="MainGrid">
        <StackPanel Name="MainStackPanel">
            <ListBox   ItemsSource="{Binding Path=Alerts}"   >
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal" >
                        </WrapPanel>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>

                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" Visibility="{Binding IsAlerting,Converter={StaticResource BooleanToVisibilityConverter}}">
                            <StackPanel Orientation="Horizontal">
                                <Button Content="{Binding BackgroundMessage}" HorizontalAlignment="Left"  Width="75"  VerticalAlignment="Top" Height="Auto"  Margin="2" 
                                    Click="{Binding ElementName=MainGrid, Path=DataContext.AlertClickCommand}" CommandParameter="{Binding}"

                                 />
                                <Label Content="{Binding OverlayMessage}" HorizontalAlignment="Left" Width="Auto" Margin="1,0,0,0" VerticalAlignment="Top" Background="Red" Foreground="White"
                                   FontWeight="Bold">
                                    <Label.Style>
                                        <Style>
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding IsAlerting}" Value="True">
                                                    <Setter  Property="Image.Visibility" Value="Visible" />
                                                    <DataTrigger.EnterActions>
                                                        <BeginStoryboard x:Name="ImageFlash">
                                                            <Storyboard>
                                                                <DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)"
                                                BeginTime="0:0:0" Duration="0:0:0.5"
                                                From="1.0" To="0.0" RepeatBehavior="Forever" AutoReverse="True"/>
                                                            </Storyboard>
                                                        </BeginStoryboard>
                                                    </DataTrigger.EnterActions>
                                                    <DataTrigger.ExitActions>
                                                        <StopStoryboard BeginStoryboardName="ImageFlash" />
                                                    </DataTrigger.ExitActions>
                                                </DataTrigger>
                                                <DataTrigger Binding="{Binding IsAlerting}" Value="False">
                                                    <DataTrigger.Setters>
                                                        <Setter  Property="Image.Visibility" Value="Collapsed" />
                                                    </DataTrigger.Setters>
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>

                                    </Label.Style>
                                </Label>
                                <Label Content="|" Margin="5"/>
                            </StackPanel>


                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>

            </ListBox>


        </StackPanel>
    </Grid>

</UserControl>

Voici ma commande

using System;
using System.Windows.Input;
using Arkle.Common;
using Arkle.SharedUI.Events;
using Arkle.SharedUI.Model;

namespace Arkle.SharedUI.ViewModel.Commands
{
    public class AlertClickCommand : ICommand
    {
        private AlertViewModel _alertViewModel;
        public AlertClickCommand(AlertViewModel alertViewModel)
        {
            _alertViewModel = alertViewModel;
        }

        public void Execute(object parameter)
        {
            if (parameter == null)
            {
                return;
            }
            var parameterAsAlert = (Alert)parameter;

            switch (parameterAsAlert.BackgroundMessage)
            {
                case "Bets":
                    EventManager.Instance.GetEvent<ShowDangerBetsRequestedEvent>().Publish(null);
                    break;
                default:
                    return;
            }
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;
    }
}

J'obtiens également l'erreur de conception suivante (voir capture d'écran) Impossible de convertir un objet de type 'System.Windows.Data.Binding' en type 'Microsoft.Expression.Markup.DocumentModel.DocumentNode'.

enter image description here

première erreur d'exécution - lance l'exécution enter image description here

Les erreurs d'exécution suivantes génèrent à plusieurs reprises: System.Windows.Markup.XamlParseException: fournissez une valeur sur 'System.Windows.Data.Binding' a levé une exception. ---> System.InvalidCastException: impossible de convertir un objet de type 'System.Reflection.RuntimeEventInfo' en type 'System.Reflection.MethodInfo'.

sur MS.Internal.Helper.CheckCanReceiveMarkupExtension (MarkupExtension markupExtension, IServiceProvider serviceProvider, DependencyObject & targetDependencyObject, DependencyProperty & targetDependencyProperty)

à System.Windows.Data.BindingBase.ProvideValue (IServiceProvider serviceProvider)

à MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue (MarkupExtension me, IServiceProvider serviceProvider)

--- Fin de la trace de la pile des exceptions internes ---

à System.Windows.FrameworkTemplate.LoadTemplateXaml (XamlReader templateReader, XamlObjectWriter currentWriter)

.......................

27
DermFrench

Vous ne liez pas une commande à la propriété Click. La propriété Click sert à ajouter un gestionnaire d'événements traditionnel à l'événement Click. Vous souhaitez utiliser la propriété Command pour lier votre commande.

<Button Content="{Binding BackgroundMessage}" 
        HorizontalAlignment="Left"  Width="75"  
        VerticalAlignment="Top" Height="Auto"  Margin="2" 
        Command="{Binding ElementName=MainGrid, 
                          Path=DataContext.AlertClickCommand}" 
        CommandParameter="{Binding}" />
53
Lee O.

Que diriez-vous de changer ce XAML:

<Button Content="{Binding BackgroundMessage}" 
        HorizontalAlignment="Left"  Width="75"  
        VerticalAlignment="Top" Height="Auto"  Margin="2" 
        Click="{Binding ElementName=MainGrid,                
                        Path=DataContext.AlertClickCommand}" 
        CommandParameter="{Binding}" />

pour ça:

<Button Content="{Binding BackgroundMessage}" 
        HorizontalAlignment="Left"  Width="75"  
        VerticalAlignment="Top" Height="Auto"  Margin="2" 
        Command="{Binding ElementName=MainGrid,                         
                          Path=DataContext.AlertClickCommand}" 
        CommandParameter="{Binding}" />
11
yambe2002