我想在WPF C#应用程序中添加一项功能,允许用户执行以下操作:
当您按下按钮时,会在画布的角落创建一个文本框,当您完成输入并再次按下该按钮时,下一次单击将在画布上设置此文本框的新位置。
我尝试编写代码但看起来不太稳定,而且我得到了一个错误,如下所示:
int i = 0;
System.Windows.Point currentPoint = new System.Windows.Point();
private void button1_Click(object sender, RoutedEventArgs e, System.Windows.Input.MouseEventArgs e2)
{
i = i + 1;
if (i == 1)
{
TextBlock TB = new TextBlock();
TB.Text = "Successfull";
TB.Background = Brushes.White;
TB.Name = "TextB";
myCanvas.Children.Add(TB);
Canvas.SetLeft(TB, 10);
Canvas.SetTop(TB, 10);
}
if (i == 2)
{
Thread.Sleep(500);
while (e2.LeftButton != MouseButtonState.Pressed)
{
Thread.Sleep(50);
}
if (e2.LeftButton == MouseButtonState.Pressed)
{
currentPoint = e2.GetPosition(this);
Canvas.SetLeft(TB, currentPoint.X);
Canvas.SetTop(TB, currentPoint.Y);
}
i=0;
}
}
但是我在“if”语句中声明了我的文本框(TB),所以当我尝试修改它的位置时,它被认为是未知的Canvas.SetLeft(TB, currentPoint.X);
。如果我在外面声明它,即使没有按下按钮,也会创建文本框。有什么想法吗?
此外,如果您有另一种看起来不那么难看的解决方案,请随时分享!
答案 0 :(得分:0)
潜力(但老实说,快速和肮脏的),解决方案可能是以下MainWindow.xaml:
<Window x:Class="CanvasTextBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Click="OnButtonClick" >Click Me</Button>
<Canvas Grid.Row="1" Background="LightSkyBlue"
x:Name="PositioningCanvas"
PreviewMouseUp="OnPreviewMouseUp">
<TextBox x:Name="TextBox" Visibility="Collapsed" MinWidth="80" />
</Canvas>
</Grid>
使用MainWindow.cs:
public MainWindow()
{
InitializeComponent();
}
private bool isTextEditing;
private void OnButtonClick(object sender, RoutedEventArgs e)
{
if (!isTextEditing)
{
TextBox.Visibility = Visibility.Visible;
isTextEditing = true;
}
else
{
isTextEditing = false;
}
}
private void OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
{
// As long as your TextBox.Visibility is Collapsed and the user is in 'textEditing' after the
// first click, don't handle clicks in the Canvas
if (!isTextEditing && TextBox.Visibility == Visibility.Visible)
{
Point clickPoint = e.GetPosition(PositioningCanvas);
Canvas.SetTop(TextBox, clickPoint.Y);
Canvas.SetLeft(TextBox, clickPoint.X);
}
}