首页 > 解决方案 > C# WPF:当窗口关闭时,如何调用具有数据绑定的方法?

问题描述

我使用 CaliburnMicro 为我的数据网格实现数据绑定:

<Window x:Class="TicketDemo.Views.ShellView"
        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:local="clr-namespace:TicketDemo.Views"
        mc:Ignorable="d" FontSize="20"
        Title="ShellView" Height="450" Width="800"
        Closing="{Binding Path=OnClose}">
    <Grid>
        <DataGrid x:Name="Tickets" AlternatingRowBackground="LightGray" CanUserAddRows="True"
                  AutoGenerateColumns="False"
                  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Title" Binding="{Binding Path=Title}"/>
                <DataGridTextColumn Header="Content" Binding="{Binding Path=Content}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

我尝试使用相同的数据绑定将名为 OnClose() 的方法链接到 Closing 事件。

using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TicketDemo.Models;

namespace TicketDemo.ViewModels
{
    class ShellViewModel : Screen
    {
        public BindableCollection<TicketModel> Tickets { get; set; }

        public ShellViewModel()
        {
            Tickets = SQLiteDataAccess.LoadTickets();
        }

        public void OnClose(object sender, EventArgs e)
        {
            MessageBox.Show("Window Closing");
        }
    }
}

当我调试程序时,我收到以下消息:

using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace TicketDemo.Views
{
    /// <summary>
    /// Interaction logic for ShellView.xaml
    /// </summary>
    public partial class ShellView : Window
    {
        public ShellView()
        {
            InitializeComponent();

            MessageBox.Show("Hello");
        }
    }
}

System.Windows.Markup.XamlParseException: ''在 'System.Windows.Data.Binding' 上提供值引发了异常。' 行号“9”和行位置“9”。

InvalidCastException:无法将“System.Reflection.RuntimeEventInfo”类型的对象转换为“System.Reflection.MethodInfo”类型。

回答有关此异常的问题的 SO 帖子与按钮有关,但这是一个事件,因此我认为这对解决我的问题没有帮助。

标签: c#wpfcaliburn.micro

解决方案


如果您使用的是 caliburn,则事件声明如下:

代替Closing="{Binding Path=OnClose}"

经过

cal:Message.Attach="[Event Closing] = [Action OnClose]"

(不要忘记添加xmlns:cal="http://www.caliburnproject.org"

在 ViewModel 你写:

    public void OnClose()
    {
        MessageBox.Show("Window Closing");
    }

推荐阅读