我有一个非常棘手的问题。
假设我有一个我在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>
据我所知,Textbox将其中的值保存为字符串。
现在我在文本框中输入一些文本,例如Hello World! It is a %great% day!
请注意,很大程度上被百分比所包围,当发生这种情况并且用户滚动该单词时,它会突出显示,以便用户无法编辑该特定单词,使其成为变量。我该怎么做呢?
我问这个奇怪的问题的原因是因为我有一个列表框,我可以拖动项目并将它们放入我的文本框中,但我不希望用户将变量放入另一个变量,也不能将变量放在变量之间,如果选择并且用户开始输入,它必须替换它或删除它。
以下是我的示例代码,您能告诉我我是否走在正确的轨道上。
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();
}
}
}
答案 0 :(得分:0)
<强>观强> 只要在TextBox顶部释放ListBoxItem,就可以获得鼠标事件的坐标。通过这些,您可以尝试通过计算开始和鼠标事件之间的字母来查找单词。知道了这个词,然后你可以通过用新的子串替换旧的子串来相应地改变 TextBox.Text 。
结论我不认为这种方法特别强大,因为它取决于字符的宽度,但它至少应该起作用。查看WPF TextBox API,您的努力没有高级支持。
<强>资源强> http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.aspx