Add a textbox to a wpf canvas in a position chosen by the user (C#) -
i add functionality wpf c# app allows user following:
when press button, textbox created in corner of canvas, when you're done typing , press button again, next click set new position of textbox on canvas.
i tried writing code doesn't solid, plus error explained below:
int = 0; system.windows.point currentpoint = new system.windows.point(); private void button1_click(object sender, routedeventargs e, system.windows.input.mouseeventargs e2) { = + 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; } }
however declared textbox (tb) inside of "if" statement, when try modify position, considered unknown canvas.setleft(tb, currentpoint.x);
. if declare outside, textbox created if button isn't pressed. ideas?
also if have solution looks less ugly, feel free share!
a potential (but honest quick & dirty one), solution following 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>
with mainwindow.cs this:
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) { // long textbox.visibility collapsed , user in 'textediting' after // first click, don't handle clicks in canvas if (!istextediting && textbox.visibility == visibility.visible) { point clickpoint = e.getposition(positioningcanvas); canvas.settop(textbox, clickpoint.y); canvas.setleft(textbox, clickpoint.x); } }
Comments
Post a Comment