【发布时间】:2019-06-15 04:41:07
【问题描述】:
谁能告诉我如何从事件处理程序访问外部对象?
下面的代码提供了我正在尝试做的示例。事件处理程序中对 externalClass 的引用会生成以下错误消息“名称 'externalClass' 在当前上下文中不存在”。
我已将程序集输出类型设置为控制台应用程序,以便它打印到控制台。
谁能告诉我如何最好地从事件处理程序中访问 externalClass 对象? 代码如下: XAML
<Window x:Class="AccessObjectFromEventHandler.MainWindow"
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:AccessObjectFromEventHandler"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="auto" />
<RowDefinition Height="30" />
<RowDefinition Height="Auto" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<Grid Grid.Row="1" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<Button Grid.Row="1" Grid.Column="2" Width="100" Height=" 30" Content="Click to Fire Event" Click="Button_Click"/>
</Grid>
</Grid>
C#
using System;
using System.Windows;
namespace AccessObjectFromEventHandler
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ExternalClass externalClass = new ExternalClass();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine($"Button Click Event Fired.");
externalClass.Name = "Some Name";
externalClass.ExternalClassMethod();
}
}
public partial class ExternalClass
{
public string Name { get; set; }
// The access modifier is "public" to enable access from external types.
public void ExternalClassMethod()
{
Console.WriteLine($"ExternalClassMethod executed. Name = {Name}");
}
}
}
【问题讨论】:
-
externalClass只存在于MainWindow方法的范围内。将其移至MainWindow(类)作用域并仅在 MainWindow 方法中对其进行初始化。
标签: c# wpf event-handling