我有一个非常棘手的问题要问你们。
假设我有一个在 WPF 中创建的文本框
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="465" Width="681">
<Grid>
<TextBox x:Name="textbox1"/>
</Grid>
</Window>
据我所知,文本框将其中的值作为字符串保存。
现在我在文本框中输入一些文本,例如Hello World! It is a %great% day!
请注意,great 被百分比包围,当发生这种情况并且用户滚动该单词时,它会突出显示,以便用户无法编辑该特定单词,使其成为一种变量。我该怎么办?
我问这个奇怪问题的原因是因为我有一个列表框,我可以从中拖动项目并将它们放入我的文本框中,但我不希望用户将变量放在另一个变量中,也不能在变量之间放置文本,它必须如果选择并且用户开始输入,则替换它或删除它。
这是我的示例代码,你能告诉我我是否在正确的轨道上。
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void listbox1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (listbox1.SelectedItems.Count > 0)
{
ListBoxItem mySelectedItem = listbox1.SelectedItem as ListBoxItem;
if (mySelectedItem != null)
{
DragDrop.DoDragDrop(listbox1, "%" + mySelectedItem.Content.ToString()+"%", DragDropEffects.Copy);
}
}
}
private void textbox1_DragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
}
private void textbox1_PreviewDragOver(object sender, DragEventArgs e)
{
DragEventArgs p;
p = e;
Point curpos = p.GetPosition(textbox1);
int pos1;
pos1 = textbox1.GetCharacterIndexFromPoint(curpos, true) + 1;
label1.Content = pos1.ToString();
string TEXT = textbox1.Text;
if(!textbox1.Text.Length.Equals(0))
{
string sLeft = TEXT.Substring(0, pos1);
string sRight = TEXT.Substring(pos1, TEXT.Length - pos1);
string sText = "";
int end, length;
//instrev funct
if(sLeft.Contains("%"))
{
end = sRight.IndexOf("%") +pos1;
length = end - pos1+2;
textbox1.SelectionStart = pos1-1;
textbox1.SelectionLength = length;
}
}
}
private void textbox1_Drop(object sender, DragEventArgs e)
{
string tstring;
tstring = e.Data.GetData(DataFormats.StringFormat).ToString();
}
private void textbox1_PreviewMouseMove(object sender, MouseEventArgs e)
{
Point curpos = e.GetPosition(textbox1);
int pos1;
pos1 = textbox1.GetCharacterIndexFromPoint(curpos, true) + 1;
label1.Content = pos1.ToString();
}
}
}