WPF:用主窗口生成了一个窗口,怎么在新窗口控制主窗口的textblock显示文字? 5
2个回答
展开全部
给新窗口定义事件。
这里由于字数限制,两个窗口我都用同一个类了。
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock x:Name="label" VerticalAlignment="Top" Text="Hello!" Margin="10,99,10,0" />
<TextBox x:Name="txtInput" VerticalAlignment="Center" Text="Hello!" HorizontalAlignment="Left" Height="20" Width="456"/>
<Button Content="点我" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/>
<Button Content="修改" HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button_Click_1" Margin="0,154,10,0"/>
</Grid>
</Window>
using System;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// 处理文本变化时间的委托
/// </summary>
public delegate void TextChangedHandler(object sender, TextChangedArgs e);
/// <summary>
/// 用来记录变化的文本
/// </summary>
public class TextChangedArgs : EventArgs
{
public string Text { get; set; }
public TextChangedArgs(string text)
{
Text = text;
}
}
/// <summary>
/// 文本变化事件
/// </summary>
public event TextChangedHandler TextChanged;
private void Button_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.TextChanged += Mw_TextChanged;
mw.Show();
}
/// <summary>
/// 处理TextChanged事件
/// </summary>
private void Mw_TextChanged(object sender, TextChangedArgs e)
{
this.label.Text = e.Text;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (TextChanged != null)
{
//引发事件,txtInput.Text 可以改成任意字符串
TextChanged.Invoke(this, new TextChangedArgs(txtInput.Text));
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询