You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP C#:点击左右按钮移动TextBox的实现问题求助

WPF实现TextBox左右移动示例(基于TranslateTransform)

XAML代码

<Window x:Class="TextBoxMoveDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TextBox移动示例" Height="200" Width="400">
    <Grid>
        <TextBox x:Name="txtDemo" Text="测试文本" Width="150" Height="30" Margin="20">
            <TextBox.RenderTransform>
                <!-- 定义TranslateTransform并命名,方便后台修改位置参数 -->
                <TranslateTransform x:Name="txtTransform" X="0" Y="0"/>
            </TextBox.RenderTransform>
        </TextBox>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20">
            <Button Content="MoveLeft" Click="MoveLeft_Click" Width="80" Margin="10"/>
            <Button Content="MoveRight" Click="MoveRight_Click" Width="80" Margin="10"/>
        </StackPanel>
    </Grid>
</Window>

C#后台代码

using System.Windows;
using System.Windows.Media;

namespace TextBoxMoveDemo
{
    public partial class MainWindow : Window
    {
        // 每次移动的步长,可根据需求调整
        private const int MoveStep = 20;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void MoveLeft_Click(object sender, RoutedEventArgs e)
        {
            // 向左移动:X值减少步长
            txtTransform.X -= MoveStep;
        }

        private void MoveRight_Click(object sender, RoutedEventArgs e)
        {
            // 向右移动:X值增加步长
            txtTransform.X += MoveStep;
        }
    }
}

关键注意点

  • 一定要给TextBox的RenderTransform绑定命名好的TranslateTransform,不然后台没法直接修改位置参数
  • 如果用LayoutTransform替代RenderTransform,移动时会改变TextBox在布局中的占位,可能导致其他控件跟着重新排列,按需选择即可
  • 步长数值可以随意调整,比如改成10就是每次移动10个单位

内容的提问来源于stack exchange,提问作者Swann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:25:23