How can I get the Position of textbox that has been pressed?
Ok. Delete all your code and start all over.
This is how you do a Sudoku board in WPF:
XAML:
<Window x:Class="WpfApplication4.Window17"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window17" Height="300" Width="300">
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="9" Columns="9"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{Binding Row}"/>
<Setter Property="Grid.Column" Value="{Binding Column}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Value}" VerticalAlignment="Stretch" FontSize="20" TextAlignment="Center"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
Code Behind:
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
namespace WpfApplication4
{
public partial class Window17 : Window
{
public Window17()
{
InitializeComponent();
var random = new Random();
var board = new List<SudokuViewModel>();
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
board.Add(new SudokuViewModel() {Row = i, Column = j,Value = random.Next(1,20)});
}
}
DataContext = board;
}
}
}
ViewModel:
public class SudokuViewModel:INotifyPropertyChanged
{
public int Row { get; set; }
public int Column { get; set; }
private int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
NotifyPropertyChange("Value");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
As you can see, Im in no way creating or manipulating UI elements in code. That's plain wrong in WPF. You must learn MVVM, and understand that UI is Not Data. Data is Data. UI is UI
Now, whenever you need to operate against the Value in the TextBoxes, just operate against the public int Value
property in the ViewModel. Your application logic and your UI must be completely decoupled.
Just copy and paste my code in a File -> New Project -> WPF Application
and see the results for yourself. This is how it looks in my computer:
Edit:
I have modified the sample to call a method when a Value is changed.
Please understand that you should NOT operate against the UI in WPF, but against DATA.
What you really care about is DATA (The ViewModel), not the UI itself.
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
using System;
namespace WpfApplication4
{
public partial class Window17 : Window
{
public List<SudokuViewModel> Board { get; set; }
public Window17()
{
InitializeComponent();
var random = new Random();
Board = new List<SudokuViewModel>();
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Board.Add(new SudokuViewModel()
{
Row = i, Column = j,
Value = random.Next(1,20),
OnValueChanged = OnItemValueChanged
});
}
}
DataContext = Board;
}
private void OnItemValueChanged(SudokuViewModel vm)
{
MessageBox.Show("Value Changed!\n" + "Row: " + vm.Row + "\nColumn: " + vm.Column + "\nValue: " + vm.Value);
}
}
public class SudokuViewModel:INotifyPropertyChanged
{
public int Row { get; set; }
public int Column { get; set; }
private int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
NotifyPropertyChange("Value");
if (OnValueChanged != null)
OnValueChanged(this);
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public Action<SudokuViewModel> OnValueChanged { get; set; }
}
}
How do I find the position of a cursor in a text box? C#
Regardless of whether any text is selected, the SelectionStart property represents the index into the text where you caret sits. So you can use String.Insert to inject some text, like this:
myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
How to detect position of last pressed key in a string in C#?
Look at the character before TextBox.SelectionStart.
Get the position of clicked word in textbox (Javascript)
EDITED : Heres the fiddle to select the word before the word clicked on. Note: no spans are used in this. https://jsfiddle.net/Lnkav5ca/5/
I think i understood what you're looking for. https://jsfiddle.net/Lnkav5ca/1/ I put all the clickable words in a class and add event listeners to that class. So when the word is clicked on it gets inserted into the text box.
var themaintextarea = document.getElementsByClassName('clickable');
for (var i = 0; i < themaintextarea.length; i++) {
themaintextarea[i].addEventListener('click', replace_sentence);
}
function replace_sentence(e){
console.log(e);
var themaintext = e.target.innerHTML
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
//alert(sometext);
}
How to get the textbox's id by cursor position
To catch the focused input when clicking a button, you have to listen to the mousedown
event as it fires before the input loses focus.
The click
event is too late, the input has already lost focused by that time.
To get the currently focused (active) element, one can use document.activeElement
.
So something like this :
$('#btnAdd').on('mousedown', function() {
var el = document.activeElement;
insertDataVarables(el, 'insertedText')
});
FIDDLE
Get caret position in HTML input?
-> selectionStart
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<script type = "text/javascript">
window.addEventListener ("load", function () {
var input = document.getElementsByTagName ("input");
input[0].addEventListener ("keydown", function () {
alert ("Caret position: " + this.selectionStart);
// You can also set the caret: this.selectionStart = 2;
});
});
</script>
<title>Test</title>
</head>
<body>
<input type = "text">
</body>
</html>
How to know on which letter the user clicked in a WPF TextBlock
Apperantly, The solution is quite simple and straightforward. However, It still uses TextBox and not TextBlock. The following method receives MouseButtonEventArgs from a mouse click event and the TextBox that triggered the event and return the text index on which the user clicked.
private int GetMouseClickPosition(MouseButtonEventArgs mouseButtonEventArgs,
TextBox textBox1)
{
Point mouseDownPoint = mouseButtonEventArgs.GetPosition(textBox1);
return textBox1.GetCharacterIndexFromPoint(mouseDownPoint, true);
}
How to determine the position of the cursor in KeyDown event?
the index is :
textbox1.CaretIndex
hope this is what you looking for
Related Topics
Associate a Private Key with the X509Certificate2 Class in .Net
How to Delete a Row from Gridview
Different Ways of Adding to Dictionary
How to Change the Button Text for 'Yes' and 'No' Buttons in the Messagebox.Show Dialog
How to Know the Selected Checkboxes from Within the Httppost Create Action Method
Resources for Learning C# Excel Interop
Execute Multiple Queries in Single Oracle Command in C#
Is There a C# Type for Representing an Integer Range
Threadstatic V.S. Threadlocal<T>: Is Generic Better Than Attribute
Manipulating Images with .Net Core
Getting Correct Image Rotation
How to Create a File and Any Folders, If the Folders Don't Exist
Log4Net Logging of Two Different Levels to Two Different Appenders for the Same Logger
How to Tell If a Type Is a "Simple" Type? I.E. Holds a Single Value
The JSON Value Could Not Be Converted to System.Int32
How to Parse Dates with a Suffix "Th", "St" or "Nd" on the Day of the Month
Intelligent Way of Removing Items from a List<T> While Enumerating in C#