UWP - 实现运行时鼠标调整 TextBox 宽度

  先来个吐槽,果然是微软自家的东西吗,所以 C# 和 VB 文档比 C++/CX 语言详细很多。。。还有 UWP 果然没人用吧。

  如何调整一个文本框的宽度呢,我有两种方案。

  第一种方案需要用到这几个方法(TextBox xmal 中 按F4,小闪电里面可看到这几个方法,该示例测试时只用到了前两个,没有处理释放事件等):

   xmal :

<TextBox x:Name="testTextBox" Width="300" PointerPressed="testTextBox_PointerPressed" PointerMoved="testTextBox_PointerMoved" />

  C# 编写逻辑:

// ....
private double prev_position;

private void testTextBox_PointerPressed(object sender, PointerRoutedEventArgs e)
{
	var textBox = (TextBox)sender;
	PointerPoint ptr = e.GetCurrentPoint(textBox);
			
	if (ptr.Position.X > textBox.Width - 2) // 鼠标从右边框处开始拖动
	{
		prev_position = ptr.Position.X;
	}
}

private void testTextBox_PointerMoved(object sender, PointerRoutedEventArgs e)
{
	PointerPoint ptr = e.GetCurrentPoint((TextBox)sender);
	if (e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
	{
		if (ptr.Properties.IsLeftButtonPressed)
		{
			((TextBox)sender).Width += ptr.Position.X - prev_position;
			prev_position = ptr.Position.X;
		}
	}
}
//...

  因为 TextBox 不同于普通控件,具有默认的 Press 事件,所以我们应该给它添加事件 handler,以保证能触发指针按下和移动事件:

testTextBox.AddHandler(PointerPressedEvent, new PointerEventHandler(testTextBox_PointerPressed), true);
testTextBox.AddHandler(PointerMovedEvent, new PointerEventHandler(testTextBox_PointerMoved), true);

  实际效果(因为有居中效果,所以默认两边同时减小,如果没有居中则左边不会动):

   第二种方法使用这些方法(该示例测试中仅用到了 ManipulationDelta):

   xmal:

<TextBox x:Name="testTextBox" Width="300" ManipulationMode="All" ManipulationDelta="testTextBox_ManipulationDelta"/>

  注意到有个 ManipulationMode="All" 属性,这是指允许我们的对该控件执行哪些类型的操作,这里我选择 All,或许用 Translation 更合理。

  C#:

private void testTextBox_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
	var textBox = (TextBox)sender;
	if (e.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
	{
		textBox.Width += e.Delta.Translation.X;
	}
}

  同前面,也为其注册事件 handle,注意,Delta event 不需要注册也可以触发该事件,但我试过,去掉注册触发事件,反应明显不灵敏:

testTextBox.AddHandler(ManipulationDeltaEvent, new ManipulationDeltaEventHandler(testTextBox_ManipulationDelta), true);

  添加触发事件的效果:

   未添加触发事件效果(明显拖得比较累):

  需要注意,上面示例都没有处理当被拖到 width < 0 的情况(会出现参数异常错误)。

  我有这个需求是因为我写的歌词制作软件需要靠文本框的宽度以及位置计算出歌词的持续时间,于是就有如下所示:

  最后再吐槽一句,UWP 的 TextBox 不能更改悬浮时的鼠标样式!!!因为悬浮在文本框上时变为文本鼠标具有最高优先级,无论怎么做都会被覆盖掉。。。除非自己重写一个控件吧。。。还有,其实 UWP 开发真的很轻松,可能是软件不复杂的原因,但它给予开发者的创作与设计理念真的很棒、很合理。但最大的两个问题就是不能做多少底层的事情(还有一些地方不如 js 开发网页版方便)以及该领域毫无前景。

猜你喜欢

转载自www.cnblogs.com/darkchii/p/12549619.html
UWP