gpt4 book ai didi

wpf - 放置鼠标指针或键盘(箭头键即 -> 和 <-)光标时从 wPF 组合框中拾取值(C#3.0)

转载 作者:行者123 更新时间:2023-12-04 06:47:45 25 4
gpt4 key购买 nike

我有一个 WPF 组合框

<ComboBox Name="cmbExpression" IsEditable="True"/> 

现在我在那边写了一些文字说 fx(a,b,c) ,f(x),x,p,mv,P#,Fx(X),x,sometext
现在我的要求是,每当 光标或鼠标(箭头键即 -> 和 <-)将放在字符上,我应该可以得到值。

一些测试用例:

案例1:
User put the cursor or mouse pointer on x of f(x).

Output will be f(x).

案例2:
User put on v of mv

Output: mv

案例3:
User put the cursor on t of sometext.

Output: sometext

案例 4:
User put the cursor on ( on Fx(X)

Output: Fx(X)

案例 5:
    User put the cursor on ',' of  fx(a,b,c) 

Output: fx(a,b,c)

我正在使用 C#3.0 和 WPF

需要帮助。

谢谢

最佳答案

TextBox 有一个方法叫做 GetCharacterIndexFromPoint在提供的位置返回字符索引,TextBlock 有一个类似的方法,它返回一个 TextPointer。您可以使用这些方法来查找光标下的内容。

<ComboBox IsEditable="True" MouseMove="ComboBox_MouseMove" />

代码
private void ComboBox_MouseMove(object sender, MouseEventArgs e)
{
var combobox = (ComboBox)sender;
//An editable ComboBox uses a TextBox named PART_EditableTextBox
var textbox = (TextBox)combobox.Template.FindName("PART_EditableTextBox", combobox);

var pos = textbox.GetCharacterIndexFromPoint(e.GetPosition(textbox),true);
var text = textbox.Text;
if (string.IsNullOrEmpty(text))
return;

txt.Text = GetWordAtPos(text,pos);
}

private static string GetWordAtPos(string str, int pos)
{
Stack<char> matches = new Stack<char>();
int wordStart = 0, wordEnd = 0;
for (int i = 0; i < str.Length - 1 && wordEnd == 0; i++)
{
char c = str[i];

switch (c)
{
case ',':
if (matches.Count == 0)
{
if (i > pos)
wordEnd = i;
else
wordStart = i;
}
break;
case '(':
matches.Push(')');
break;
case ')':
if (matches.Count == 0 || matches.Peek() != c)
throw new ArgumentException("Found ) without matching ( character.");
else
matches.Pop();
break;
}
}

string word;
if (wordEnd == 0)
word = str.Substring(wordStart);
else
word = str.Substring(wordStart, wordEnd - wordStart);

return word.Trim(',');
}

如果您需要对每个标记的外观进行更多控制,您可能想要研究的另一种方法是为每个标记生成一个 Run 元素,但这似乎适用于您描述的情况。

关于wpf - 放置鼠标指针或键盘(箭头键即 -> 和 <-)光标时从 wPF 组合框中拾取值(C#3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3532104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com