WPF关于WindowInteropHelper的一个BUG

在Windows SDK中关于WindowInteropHelper类的介绍中,关于其Owner属性的说明和实现有些问题。

原文是:An example scenario is if you need to host a WPF dialog box in a Win32 application. Initialize the WindowInteropHelper with a WPF window object for the dialog. You can then get the WPF window's handle (HWND) from the Handle property and specify the owner for the WPF window with the Owner property. The following code example shows how to use WindowInteropHelper when hosting a WPF dialog box in a Win32 application.

大意是通过WindowInteropHelper的Owner属性可以把WPF窗口的Owner属性设置为一个Win32的窗口句柄HWND。但是这个功能的实现是有问题的。有兴趣的朋友可以通过下面的代码进行测试:

Window myDialog = new Window();
myDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
WindowInteropHelper wih = new WindowInteropHelper(myDialog);
wih.Owner = ownerHwnd;
myDialog.ShowDialog();

这段代码最后显示的窗口不会位于Owner窗口的中心。事实上,WindowInteropHelper.Owner属性设置的是Window类的_ownerHandle成员。这个成员和Window.Owner设置的成员不是同一个。因此,文档中的说明和WPF的实际实现不相符的。这个问题基本已经确认是WPF的一个BUG。 

Windows Presentation Foundation (WPF)中,创建一个TextBox控件非常简单。TextBox是一个让用户输入文本的用户界面元素。以下是步骤和基本XAML代码示例: 1. 首先,在Visual Studio或其他支持WPF的IDE中打开一个新的WPF项目。 2. 在XAML文件(如`Window1.xaml`)中,添加一个`<Window>`标签作为根元素,并设置一些基本属性,比如标题和宽度高度等: ```xml <Window x:Class="YourNamespace.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="My WPF TextBox Example" Height="450" Width="800"> </Window> ``` 3. 然后,在窗体中添加TextBox控件,通过`<TextBox>`标签完成: ```xml <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <!-- Add more rows if needed --> </Grid.RowDefinitions> <TextBox Grid.Row="0" Margin="10" Name="textBox1" PlaceholderText="Enter some text here" /> </Grid> ``` 在这个例子中,TextBox放在了一个Grid容器内,设置了默认行高为自适应。`Name`属性用于后期对TextBox进行程序控制,`PlaceholderText`属性则显示提示信息。 4. 最后,在对应的`Window1.xaml.cs`背后编写C#代码,如果需要响应用户输入事件,可以这样做: ```csharp using System.Windows; namespace YourNamespace { public partial class Window1 : Window { public Window1() { InitializeComponent(); textBox1.TextChanged += textBox1_TextChanged; // Adding a TextChanged event handler } private void textBox1_TextChanged(object sender, TextChangedEventArgs e) { // Handle the text change event here Debug.WriteLine($"Text changed: {textBox1.Text}"); } } } ``` 现在,当你运行这个WPF应用程序时,就会看到一个带有提示文本的TextBox,用户可以在其中输入文本,而且当文本内容发生变化时,你会在控制台看到相关信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值