【问题标题】:Command binding Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'命令绑定无法将“System.Reflection.RuntimeEventInfo”类型的对象转换为“System.Reflection.MethodInfo”类型
【发布时间】:2014-08-31 21:07:35
【问题描述】:

当我通过 XAML 将按钮连接到命令时,出现运行时错误 System.Windows.Markup.XamlParseException:在“System.Windows.Data.Binding”上提供值引发异常。 ---> System.InvalidCastException:无法将“System.Reflection.RuntimeEventInfo”类型的对象转换为“System.Reflection.MethodInfo”类型。

当我删除 XAML 中的命令绑定时,一切正常,并且我的项目显示等。 这是命令绑定:

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

连接视图模型的代码(在我的窗口后面的代码中):

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

这是我的视图模型我的视图模型是我的视图的数据上下文

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));
        }
    }
}

这是我的 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>

这是我的命令

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;
    }
}

我还收到以下设计时错误(见屏幕截图) 无法将“System.Windows.Data.Binding”类型的对象转换为“Microsoft.Expression.Markup.DocumentModel.DocumentNode”类型。

第一个运行时错误 - 引发运行

重复抛出后续运行时错误: System.Windows.Markup.XamlParseException:在“System.Windows.Data.Binding”上提供值引发异常。 ---> System.InvalidCastException:无法将“System.Reflection.RuntimeEventInfo”类型的对象转换为“System.Reflection.MethodInfo”类型。

在 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)

---内部异常堆栈跟踪结束---

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

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

【问题讨论】:

  • 您在哪里以及如何设置您的DataContext?您的视图模型代码(至少是属性)在哪里?看在上帝的份上,请删除那个可笑的长堆栈跟踪,除非您打算让用户阅读您的问题。
  • 嗨,我已经修改了问题以显示正在设置的数据上下文。

标签: c# wpf xaml binding command


【解决方案1】:

您没有将命令绑定到Click 属性。 Click 属性用于向Click 事件添加传统的事件处理程序。您想使用Command 属性来绑定您的命令。

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

【讨论】:

  • 这只是发生在我身上 CheckBox... 我绑定到 Checked 而不是 IsChecked 并在其他地方寻找问题,直到我仔细查看异常,转向谷歌并登陆这里:) 在 2016 年仍然有用
  • 多年以后。
  • "... 这就是本应成为答案的评论的传奇开始了——他的故事被讲述了很多年。酒馆里的吟游诗人唱着关于它的歌,所有那些听他们会举起他们的咖啡杯并大喊UPVOTE!UPVOTE!UPVOTE!”
【解决方案2】:

如何更改此 XAML:

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

到这里:

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

【讨论】:

  • 重复第一个答案 - 但我看到它是在另一个答案之后仅 3 分钟发布的,所以当另一个人击败你时,你很可能正在发帖,所以我赢了不要投反对票,而是投赞成票:)
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
相关资源
最近更新 更多