c# - 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 帖子与按钮有关,但这是一个事件,因此我认为这对解决我的问题没有帮助。
解决方案
如果您使用的是 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");
}
推荐阅读
- search - 没有或无限 end_date 的 SOLR 日期范围
- sql - 如何在 SQL Join 中编写可选条件
- google-ads-api - 在多个应用中使用谷歌广告开发者令牌
- c# - 保持对嵌套列表的引用
在 C# 中 - shopify - 如何在shopify的集合页面上显示产品变体
- laravel - 阻止用户回复电子邮件
- java - 无法通过 Docker 使用 Gradle 构建 Java 16 应用程序
- javascript - ReactJS:渲染数据的函数
- php - 在 PHP 中将 mcrypt_encrypt 转换为 openssl_encrypt
- java - 如何将 IDE 中显示的 Logger 消息从 Java 获取到 Vue 前端