confused over casting between custom object and UIElement - c#

my prog adds objects to a canvas of type grid, instances are called vgridcargo.
I can remove them by double tapping no problem.
However, they also populate a listview and would like to remove them from canvas from here also.
the issue I am having is how to a determine the index location of that specific vgridcargo (Grid) object in the canvas.
Any help is greatly appreciated. Thanks
If I cast it to a UIElement all items come back as -1
var objectToDelete = sender as UIElement;
//string objID = objectToDelete.vCargoID;
ShowMessage("element is at index" + _canvasref.Children.IndexOf(objectToDelete));
if I leave it as I get
"Cannot Convert from VGridCargo to Windows.UI.XAML.UI.Element"
var objectToDelete = sender as VGridCargo;
//string objID = objectToDelete.vCargoID;
ShowMessage("element is at index" + _canvasref.Children.IndexOf(objectToDelete));
`vgridcargo`. Class
class VGridCargo
{
private Grid cargo;
private Canvas _canvasRef;
private double vCargoWidth;
private double vCargoHeight;
private Brush vCargoColour;
public bool vCargoHeavy;
public string vCargoDG;
public string vCargoID;
public string vCargoImgPath;
public double vTonnage;
private bool isActive;
// private static Dictionary<string,object> = new
private TextBlock vText = new TextBlock();
private Windows.UI.Input.PointerPoint startPoint;
private Point transOrigin = new Point(0.5, 0.5);
private RotateTransform cargoRotate = new RotateTransform
{
CenterX=0,
CenterY=0,
Angle=90,
};
/*public VGridCargo(Canvas canvas)
{
_canvasRef = canvas;
}*/
public VGridCargo(Canvas canvas, double inHeight, double inWidth, Brush inColor, bool inHLift, string inPath, string inID,double inTonnage)
{
_canvasRef = canvas;
vCargoWidth = inWidth;
vCargoHeight = inHeight;
vCargoColour = inColor;
vCargoHeavy = inHLift;
//vCargoDG = inDG;
vCargoImgPath = inPath;
vCargoID = inID;
vTonnage = inTonnage;
}
public void CreateCargo()
{
cargo = new Grid();
//Properties
cargo.Height = Ratioconvert(vCargoHeight);
cargo.Width = Ratioconvert(vCargoWidth);
cargo.Name = vCargoID;
cargo.Children.Add(vText);
vText.FontSize = 5;
vText.Text= vCargoID;
//** Look into sort out color's and brush's in program mixed api's?
Color myColor = (vCargoColour as SolidColorBrush).Color;
cargo.Background = new SolidColorBrush(myColor);
cargo.CanDrag = true;
//Handlers
cargo.RightTapped += Cargo_RightTapped;
cargo.PointerPressed += Cargo_PointerPressed;
cargo.PointerMoved += Cargo_PointerMoved;
cargo.PointerReleased += Cargo_PointerReleased;
cargo.DoubleTapped += Cargo_DoubleTapped;
// vText.PointerEntered += VText_PointerEntered;
//vText.PointerExited += VText_PointerExited;
Canvas.SetLeft(cargo, 0);
Canvas.SetTop(cargo, 0);
_canvasRef.Children.Add(cargo);
Stats.SetCargoCount();
Stats.SetTonnageCount(vTonnage);
if (vCargoHeavy)
{
Stats.SetHLCount();
}
if (!(vCargoDG==null))
{
Stats.SetDGCount();
}
}
code here

Related

Custom Selector control does not update after ItemsSource has been set?

I've put together a custom control in WPF in C# based on the Selector primitive:
public class PadControl : Selector
{
private const int padWidth = 28;
private const int padHeight = 18;
private const int padGap = 5;
private double _width;
private double _height;
static PadControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PadControl), new FrameworkPropertyMetadata(typeof(PadControl),
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender));
}
public PadControl()
{
}
protected override Size MeasureOverride(Size constraint)
{
_width = constraint.Width;
_height = constraint.Height;
return base.MeasureOverride(constraint);
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
var numHorz = _width / (padWidth + padGap);
var numVert = Math.Min(_height / (padHeight + padGap), 16);
var pen = new Pen(Brushes.Black, 1.0);
var brush = new SolidColorBrush(Color.FromRgb(192, 192, 192));
for(int bar = 0; bar < numHorz; bar++)
{
for(int track = 0; track < numVert; track++)
{
var rect = GetPadRect(bar, track);
dc.DrawRectangle(brush, pen, rect);
}
}
if (Items == null)
return;
brush = new SolidColorBrush(Colors.LightYellow);
var typeface = new Typeface("Tahoma");
foreach(PadViewModel item in Items)
{
var rect = GetPadRect(item.Bar, item.Track);
dc.DrawRectangle(brush, pen, rect);
var formatted = new FormattedText(item.Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 12, Brushes.Black, 1.0)
{
MaxTextWidth = padWidth,
TextAlignment = TextAlignment.Center
};
dc.DrawText(formatted, GetPadPoint(item.Bar, item.Track));
}
}
private Rect GetPadRect(int bar, int track)
{
var rect = new Rect(bar * (padWidth + padGap) + padGap, track * (padHeight + padGap) + padGap, padWidth, padHeight);
return rect;
}
private Point GetPadPoint(int bar, int track)
{
var point = new Point(bar * (padWidth + padGap) + padGap, track * (padHeight + padGap) + padGap);
return point;
}
}
This draws as I'd like it, but it doesn't draw the items until I resize the control.
When the control renders for the first time, it doesn't render any Items as that is empty. Items is populated indirectly with this:
<controls:PadControl Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Pads}"/>
The problem is, I don't see an update come through after ItemsSource has been set. So the question is, how do I attach an event handler to catch this? Do I attach it to Items or to ItemsSource?
The answer is to override OnItemsSourceChanged as described by Keith Stein in the comments above.

Why I cannot create more PictureBox in my array?

First of all I want to thank you for your time :) So there is my problem.. I am trying to make a little game where I spawn PictureBox and send it from right to left and my player which will be a PictureBox will try to avoid them jumping. So the first thing I did is , I created my PictureBox spawner with a class .. But the problem is , I can only spawn block[0] .. when I try to create block[1], nothing happens !! Please help me.. There is my code :
Form1.cs
namespace Game_0._1
{
public partial class Form1 : Form
{
Block[] block = new Block[50];
public Form1()
{
InitializeComponent();
int _Length = block.Length;
for(int i=0; i < 50; i++)
{
block[i] = new Block();
this.Controls.Add(block[i]._ScreenPanel());
block[i].Screen.Controls.Add(block[i].Box);
label1.Text = ("Generating block [" + i + "]");
}
}
private void button1_Click(object sender, EventArgs e)
{
block[0].SpawnBlock();
}
}
}
Block.cs
namespace Game_0._1
{
class Block
{
public Panel Screen;
public PictureBox Box;
Point x = new Point(50, 50);
Size s = new Size(150, 50);
Color c = Color.FromName("black");
public Block()
{
Screen = new Panel();
Screen.Dock = DockStyle.Fill;
Box = new PictureBox();
}
public Panel _ScreenPanel()
{
return Screen;
}
public PictureBox SpawnBlock()
{
Box.Name = "Obstacle";
Box.Location = x;
Box.Size = s;
Box.BorderStyle = BorderStyle.FixedSingle;
Box.BackColor = c;
return Box;
}
public void ChangeXLoc()
{
this.x.X += 50;
}
}
}
Here :
private void button1_Click(object sender, EventArgs e)
{
block[0].SpawnBlock();
}
this spawn a black box successfully , but if I type block[1], nothing ...
The issue is that your Panel (Screen) is overlapping the Panel that box[1] is positioned in, as a result it is not visible unless brought to front - which will in turn make the other box invisible instead.
A solution to this is to use a single panel, and size it accordingly, this allows you to place each box on the same panel and have their position relative to the Panel's 0,0.
Another solution would be to have a panel for each box which is the same size as the box and move the Panel and not the box which will have the same effect, but likely require less code to be edited.
I modified your code a little maybe it helps:
your form :
public partial class Form1 : Form
{
private Block[] _block = new Block[50];
private Point _x = new Point(0, 50);
private Timer _timer=new Timer();
private int _index = 0;
public Form1()
{
InitializeComponent();
_timer.Interval = 1000;
_timer.Tick += _timer_Tick;
for (int i = 0; i < 50; i++)
{
_block[i] = new Block(_x);
//Move the position of the block
ChangeXLoc();
Controls.Add(_block[i]._ScreenPanel());
label1.Text = #"Generating block [" + i + #"]";
}
}
//Timer to spawn the blocks
private void _timer_Tick(object sender, EventArgs e)
{
_block[_index].SpawnBlock();
if (_index < 49)
_index++;
}
private void button1_Click(object sender, EventArgs e)
{
_timer.Start();
}
private void ChangeXLoc()
{
_x.X += 50;
}
}
and your block class :
class Block
{
Panel Screen;
PictureBox Box;
Point _x;
Size s = new Size(50, 50);
Color c = Color.FromName("black");
//Pass the position x to the block
public Block(Point x)
{
_x = x;
Screen = new Panel
{
Size = s
};
}
public Panel _ScreenPanel()
{
Screen.Location = _x;
return Screen;
}
public void SpawnBlock()
{
Box = new PictureBox
{
Dock = DockStyle.Fill,
Name = "Obstacle" + _x,
BorderStyle = BorderStyle.FixedSingle,
BackColor = c
};
Screen.Controls.Add(Box);
}
}

How to Pass and Set values to Usercontrol in wpf

How to Pass and Set values to Usercontrol.
Here I have two question regarding a WPF project.
Overview:
In this project, I'm trying to use a Usercontrol as a resources on a canvas and connecting them with each other by LineGeometry. 'MyThumb' class i'm using to make control dragable and control set values.
where i'm using overrided 'OnApplyTemplate' method to pass values on the Usercontrol. To set value i'm using 'Template.FindName'. Here it is returning null.
Now the question is 'how to set values on usercontrol' in the code below:
Another question is related to line color. In the project i'm using LineGeometry to display lines between usercontrols but not able to change line colors.. want to set different lines with different color.
Here the question is how to change color of existing LineGeometry.
Please have a look to the codes i'm using:
Mythumb.cs
public class MyThumb : Thumb
{
#region Properties
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyThumb), new UIPropertyMetadata(""));
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(string), typeof(MyThumb), new UIPropertyMetadata(""));
// This property will hanlde the content of the textblock element taken from control template
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
// This property will handle the content of the image element taken from control template
public string ImageSource
{
get { return (string)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public Point MyLocation
{
get
{
Point nm = new Point(Canvas.GetLeft(this), Canvas.GetTop(this));
return nm;
}
}
public List<LineGeometry> EndLines { get; private set; }
public List<LineGeometry> StartLines { get; private set; }
#endregion
#region Constructors
public MyThumb()
: base()
{
StartLines = new List<LineGeometry>();
EndLines = new List<LineGeometry>();
}
public MyThumb(string title, string imageSource, Point position)
: this()
{
//Setting ControlTemplate as Usercontrol 'ContactNode'
ControlTemplate templatex = new ControlTemplate();
var fec = new FrameworkElementFactory(typeof(ContactNode));
templatex.VisualTree = fec;
this.Template = templatex;
this.Title = (title != null) ? title : string.Empty;
this.ImageSource = (imageSource != null) ? imageSource : string.Empty;
this.SetPosition(position);
}
public MyThumb( string title, string imageSource, Point position, DragDeltaEventHandler dragDelta)
: this(title, imageSource, position)
{
this.DragDelta += dragDelta;
}
#endregion
// Helper method for setting the position of our thumb
public void SetPosition(Point value)
{
Canvas.SetLeft(this, value.X);
Canvas.SetTop(this, value.Y);
}
#region Linking logic
// This method establishes a link between current thumb and specified thumb.
// Returns a line geometry with updated positions to be processed outside.
public LineGeometry LinkTo(MyThumb target)
{
// Create new line geometry
LineGeometry line = new LineGeometry();
// Save as starting line for current thumb
this.StartLines.Add(line);
// Save as ending line for target thumb
target.EndLines.Add(line);
// Ensure both tumbs the latest layout
this.UpdateLayout();
target.UpdateLayout();
// Update line position
line.StartPoint = new Point(Canvas.GetLeft(this) + this.ActualWidth / 2, Canvas.GetTop(this) + this.ActualHeight / 2);
line.EndPoint = new Point(Canvas.GetLeft(target) + target.ActualWidth / 2, Canvas.GetTop(target) + target.ActualHeight / 2);
// return line for further processing
return line;
}
// This method establishes a link between current thumb and target thumb using a predefined line geometry
// Note: this is commonly to be used for drawing links with mouse when the line object is predefined outside this class
public bool LinkTo(MyThumb target, LineGeometry line)
{
// Save as starting line for current thumb
this.StartLines.Add(line);
// Save as ending line for target thumb
target.EndLines.Add(line);
// Ensure both tumbs the latest layout
this.UpdateLayout();
target.UpdateLayout();
// Update line position
line.StartPoint = new Point(Canvas.GetLeft(this) + this.ActualWidth / 2, Canvas.GetTop(this) + this.ActualHeight / 2);
line.EndPoint = new Point(Canvas.GetLeft(target) + target.ActualWidth / 2, Canvas.GetTop(target) + target.ActualHeight / 2);
return true;
}
#endregion
// This method updates all the starting and ending lines assigned for the given thumb
// according to the latest known thumb position on the canvas
public void UpdateLinks()
{
double left = Canvas.GetLeft(this);
double top = Canvas.GetTop(this);
for (int i = 0; i < this.StartLines.Count; i++)
this.StartLines[i].StartPoint = new Point(left + this.ActualWidth / 2, top + this.ActualHeight / 2);
for (int i = 0; i < this.EndLines.Count; i++)
this.EndLines[i].EndPoint = new Point(left + this.ActualWidth / 2, top + this.ActualHeight / 2);
}
// Upon applying template we apply the "Title" and "ImageSource" properties to the template elements.
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Access the textblock element of template and assign it if Title property defined
if (this.Title != string.Empty)
{
TextBlock txt = this.Template.FindName("tplTextBlock", this) as TextBlock;
if (txt != null) //getting null here unable to find element..
txt.Text = Title;
}
// Access the image element of our custom template and assign it if ImageSource property defined
if (this.ImageSource != string.Empty)
{
Image img = this.Template.FindName("tplImage", this) as Image;
if (img != null)
img.Source = new BitmapImage(new Uri(this.ImageSource, UriKind.Relative));
}
}
}
Window1.xaml.cs
public partial class Window1 : Window
{
// flag for enabling "New thumb" mode
bool isAddNewAction = false;
// flag for enabling "New link" mode
bool isAddNewLink = false;
// flag that indicates that the link drawing with a mouse started
bool isLinkStarted = false;
// variable to hold the thumb drawing started from
MyThumb linkedThumb;
// Line drawn by the mouse before connection established
LineGeometry link;
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Point pp = new Point(myCanvas.ActualWidth/2,myCanvas.ActualHeight/2);
AdNewNode(pp, "ACTION", "/Images/gear_connection.png");
this.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Window1_PreviewMouseLeftButtonDown);
this.PreviewMouseMove += new MouseEventHandler(Window1_PreviewMouseMove);
this.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(Window1_PreviewMouseLeftButtonUp);
}
// Event hanlder for dragging functionality support
private void onDragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
// Exit dragging operation during adding new link
if (isAddNewLink) return;
MyThumb thumb = e.Source as MyThumb;
Canvas.SetLeft(thumb, Canvas.GetLeft(thumb) + e.HorizontalChange);
Canvas.SetTop(thumb, Canvas.GetTop(thumb) + e.VerticalChange);
// Update links' layouts for active thumb
thumb.UpdateLinks();
}
// Event handler for creating new thumb element by left mouse click
// and visually connecting it to the myThumb2 element
void AdNewNode(Point nPosition,string nTitle, string nImage)
{
MyThumb newThumb = new MyThumb(
nTitle,
nImage,
nPosition,
onDragDelta);
myCanvas.Children.Add(newThumb);
}
void Window1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// If adding new action...
if (isAddNewAction)
{
AdNewNode(e.GetPosition(this), "ACTION", "/Images/gear_connection.png");
// resume common layout for application
isAddNewAction = false;
Mouse.OverrideCursor = null;
btnNewAction.IsEnabled = btnNewLink.IsEnabled = true;
e.Handled = true;
}
// Is adding new link and a thumb object is clicked...
if (isAddNewLink && e.Source.GetType() == typeof(MyThumb))
{
if (!isLinkStarted)
{
if (link == null || link.EndPoint != link.StartPoint)
{
Point position = e.GetPosition(this);
link = new LineGeometry(position, position);
//nodepath=new Path();
//nodepath.Stroke = Brushes.Pink;
//nodepath.Data = link; // Here line color is getting change but connectivity getting lost....
connectors.Children.Add(link);
//myCanvas.Children.Add(nodepath);
isLinkStarted = true;
linkedThumb = e.Source as MyThumb;
e.Handled = true;
}
}
}
}
// Handles the mouse move event when dragging/drawing the new connection link
void Window1_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (isAddNewLink && isLinkStarted)
{
// Set the new link end point to current mouse position
link.EndPoint = e.GetPosition(this);
e.Handled = true;
}
}
// Handles the mouse up event applying the new connection link or resetting it
void Window1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// If "Add link" mode enabled and line drawing started (line placed to canvas)
if (isAddNewLink && isLinkStarted)
{
// declare the linking state
bool linked = false;
// We released the button on MyThumb object
if (e.Source.GetType() == typeof(MyThumb))
{
MyThumb targetThumb = e.Source as MyThumb;
// define the final endpoint of line
link.EndPoint = e.GetPosition(this);
// if any line was drawn (avoid just clicking on the thumb)
if (link.EndPoint != link.StartPoint && linkedThumb != targetThumb)
{
// establish connection
linkedThumb.LinkTo(targetThumb, link);
// set linked state to true
//nodepath = new Path();
//nodepath.Stroke = Brushes.Pink;
//nodepath.Data = link;
linked = true;
}
}
// if we didn't manage to approve the linking state
// button is not released on MyThumb object or double-clicking was performed
if (!linked)
{
// remove line from the canvas
//connectors.Children.Remove(link);
// clear the link variable
link = null;
}
// exit link drawing mode
isLinkStarted = isAddNewLink = false;
// configure GUI
btnNewAction.IsEnabled = btnNewLink.IsEnabled = true;
Mouse.OverrideCursor = null;
e.Handled = true;
}
//this.Title = "Links established: " + connectors.Children.Count.ToString();
}
// Event handler for enabling new thumb creation by left mouse button click
private void btnNewAction_Click(object sender, RoutedEventArgs e)
{
isAddNewAction = true;
Mouse.OverrideCursor = Cursors.SizeAll;
btnNewAction.IsEnabled = btnNewLink.IsEnabled = false;
}
private void btnNewLink_Click(object sender, RoutedEventArgs e)
{
isAddNewLink = true;
Mouse.OverrideCursor = Cursors.Cross;
btnNewAction.IsEnabled = btnNewLink.IsEnabled = false;
}
}
Please try to correct me where i'm doing wrong in this code.

How to give focus to the inputbox for ASP.NET in C#?

I was trying to find out how to create an input messagebox in C#.
I found the solution which uses the inputbox of visualbasic.
I will tell how to do for those who are not aware.
Add Microsoft VisualBasic dll to your project. Use the namespace where you need it.
protected void btnUpdateComment_Click(object sender, EventArgs e)
{
string str = Microsoft.VisualBasic.Interaction.InputBox("", "Edit your comment and Click Ok", "Default");
label1.Text = str;
}
You see the codes above are about WinForm. But how to cope with that in an ASP.NET?
Unfortunately C# doesn't have its own implementation of the InputBox method so what you have is correct:
Microsoft.VisualBasic.Interaction.InputBox("How Old are you?","Age Box","22")
However if you add a using statement you can have shorter syntax in your code
using Microsoft.VisualBasic;
public void Message()
{
Interaction.InputBox("How Old are you?","Age Box","22");
}
Here is a duplicate of the question:
What is the C# version of VB.net's InputDialog?
And a Social.Msdn post:
Social MSDN Link
Create A InputBox Class and Use It.
You Won't have Focus problem here
Source
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsApplication1
{
#region InputBox return result
/// <summary>
/// Class used to store the result of an InputBox.Show message.
/// </summary>
public class InputBoxResult
{
public DialogResult ReturnCode;
public string Text;
}
#endregion
/// <summary>
/// Summary description for InputBox.
/// </summary>
public class InputBox
{
#region Private Windows Contols and Constructor
// Create a new instance of the form.
private static Form frmInputDialog;
private static Label lblPrompt;
private static Button btnOK;
private static Button btnCancel;
private static TextBox txtInput;
public InputBox()
{
}
#endregion
#region Private Variables
private static string _formCaption = string.Empty;
private static string _formPrompt = string.Empty;
private static InputBoxResult _outputResponse = new InputBoxResult();
private static string _defaultValue = string.Empty;
private static int _xPos = -1;
private static int _yPos = -1;
#endregion
#region Windows Form code
private static void InitializeComponent()
{
// Create a new instance of the form.
frmInputDialog = new Form();
lblPrompt = new Label();
btnOK = new Button();
btnCancel = new Button();
txtInput = new TextBox();
frmInputDialog.SuspendLayout();
//
// lblPrompt
//
lblPrompt.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom) | AnchorStyles.Left) | AnchorStyles.Right)));
lblPrompt.BackColor = SystemColors.Control;
lblPrompt.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, ((Byte)(0)));
lblPrompt.Location = new Point(12, 9);
lblPrompt.Name = "lblPrompt";
lblPrompt.Size = new Size(302, 82);
lblPrompt.TabIndex = 3;
//
// btnOK
//
btnOK.DialogResult = DialogResult.OK;
btnOK.FlatStyle = FlatStyle.Popup;
btnOK.Location = new Point(326, 8);
btnOK.Name = "btnOK";
btnOK.Size = new Size(64, 24);
btnOK.TabIndex = 1;
btnOK.Text = "&OK";
btnOK.Click += new EventHandler(btnOK_Click);
//
// btnCancel
//
btnCancel.DialogResult = DialogResult.Cancel;
btnCancel.FlatStyle = FlatStyle.Popup;
btnCancel.Location = new Point(326, 40);
btnCancel.Name = "btnCancel";
btnCancel.Size = new Size(64, 24);
btnCancel.TabIndex = 2;
btnCancel.Text = "&Cancel";
btnCancel.Click += new EventHandler(btnCancel_Click);
//
// txtInput
//
txtInput.Location = new Point(8, 100);
txtInput.Name = "txtInput";
txtInput.Size = new Size(379, 20);
txtInput.TabIndex = 0;
txtInput.Text = "";
//
// InputBoxDialog
//
frmInputDialog.AutoScaleBaseSize = new Size(5, 13);
frmInputDialog.ClientSize = new Size(398, 128);
frmInputDialog.Controls.Add(txtInput);
frmInputDialog.Controls.Add(btnCancel);
frmInputDialog.Controls.Add(btnOK);
frmInputDialog.Controls.Add(lblPrompt);
frmInputDialog.FormBorderStyle = FormBorderStyle.FixedDialog;
frmInputDialog.MaximizeBox = false;
frmInputDialog.MinimizeBox = false;
frmInputDialog.Name = "InputBoxDialog";
frmInputDialog.ResumeLayout(false);
}
#endregion
#region Private function, InputBox Form move and change size
static private void LoadForm()
{
OutputResponse.ReturnCode = DialogResult.Ignore;
OutputResponse.Text = string.Empty;
txtInput.Text = _defaultValue;
lblPrompt.Text = _formPrompt;
frmInputDialog.Text = _formCaption;
// Retrieve the working rectangle from the Screen class
// using the PrimaryScreen and the WorkingArea properties.
System.Drawing.Rectangle workingRectangle = Screen.PrimaryScreen.WorkingArea;
if((_xPos >= 0 && _xPos < workingRectangle.Width-100) && (_yPos >= 0 && _yPos < workingRectangle.Height-100))
{
frmInputDialog.StartPosition = FormStartPosition.Manual;
frmInputDialog.Location = new System.Drawing.Point(_xPos, _yPos);
}
else
frmInputDialog.StartPosition = FormStartPosition.CenterScreen;
string PrompText = lblPrompt.Text;
int n = 0;
int Index = 0;
while(PrompText.IndexOf("\n",Index) > -1)
{
Index = PrompText.IndexOf("\n",Index)+1;
n++;
}
if( n == 0 )
n = 1;
System.Drawing.Point Txt = txtInput.Location;
Txt.Y = Txt.Y + (n*4);
txtInput.Location = Txt;
System.Drawing.Size form = frmInputDialog.Size;
form.Height = form.Height + (n*4);
frmInputDialog.Size = form;
txtInput.SelectionStart = 0;
txtInput.SelectionLength = txtInput.Text.Length;
txtInput.Focus();
}
#endregion
#region Button control click event
static private void btnOK_Click(object sender, System.EventArgs e)
{
OutputResponse.ReturnCode = DialogResult.OK;
OutputResponse.Text = txtInput.Text;
frmInputDialog.Dispose();
}
static private void btnCancel_Click(object sender, System.EventArgs e)
{
OutputResponse.ReturnCode = DialogResult.Cancel;
OutputResponse.Text = string.Empty; //Clean output response
frmInputDialog.Dispose();
}
#endregion
#region Public Static Show functions
static public InputBoxResult Show(string Prompt)
{
InitializeComponent();
FormPrompt = Prompt;
// Display the form as a modal dialog box.
LoadForm();
frmInputDialog.ShowDialog();
return OutputResponse;
}
static public InputBoxResult Show(string Prompt,string Title)
{
InitializeComponent();
FormCaption = Title;
FormPrompt = Prompt;
// Display the form as a modal dialog box.
LoadForm();
frmInputDialog.ShowDialog();
return OutputResponse;
}
static public InputBoxResult Show(string Prompt,string Title,string Default)
{
InitializeComponent();
FormCaption = Title;
FormPrompt = Prompt;
DefaultValue = Default;
// Display the form as a modal dialog box.
LoadForm();
frmInputDialog.ShowDialog();
return OutputResponse;
}
static public InputBoxResult Show(string Prompt,string Title,string Default,int XPos,int YPos)
{
InitializeComponent();
FormCaption = Title;
FormPrompt = Prompt;
DefaultValue = Default;
XPosition = XPos;
YPosition = YPos;
// Display the form as a modal dialog box.
LoadForm();
frmInputDialog.ShowDialog();
return OutputResponse;
}
#endregion
#region Private Properties
static private string FormCaption
{
set
{
_formCaption = value;
}
} // property FormCaption
static private string FormPrompt
{
set
{
_formPrompt = value;
}
} // property FormPrompt
static private InputBoxResult OutputResponse
{
get
{
return _outputResponse;
}
set
{
_outputResponse = value;
}
} // property InputResponse
static private string DefaultValue
{
set
{
_defaultValue = value;
}
} // property DefaultValue
static private int XPosition
{
set
{
if( value >= 0 )
_xPos = value;
}
} // property XPos
static private int YPosition
{
set
{
if( value >= 0 )
_yPos = value;
}
} // property YPos
#endregion
}
}
Alwyn Miranda:
If you are using asp.net application, you should use Prompt instead of this, for "InputBox" is only for WinForm. And you can accept the value via javascript by saving into a hiddenfield and fetch the value in the Form_Load by using HiddenField's Id.Value
You obviously can't use neither a VB (or Windows.Forms) kind of inputbox on a web application. The only reason you are seeing the inputbox is because the server is probably on your own machine (is the server creating the inputbox, not the web client). If you ever run a different client from a different machine, you won't see the inputbox at all (it'll open in the server, and probably will stall waiting for the input).
You'll have to use a web browser method of inputting data, but since you are indeed trying to open a Windows form in a web application, I guess your understanding of how web client/server applications work is just wrong, and you should begin by getting to understand this, which is way beyond the scope of this question (and Stack Overflow in general).

Making text move with the rectangle it is on top of

I am new to silverlight and so I may just be missing something due to my lack of knowledge. I am writing an app that uses Rectangles that you can click and drag to around the screen after they are generated. I have function that generates the rectangles:
public void formatBox(block b)
{
Rectangle Rec = new Rectangle();
Rec.Height = 100;
Rec.Width = 200;
SolidColorBrush newBrush = new SolidColorBrush();
newBrush.Color = b.blockColor;
SolidColorBrush blackBrush = new SolidColorBrush();
blackBrush.Color = Colors.Black;
Rec.StrokeThickness = 4;
Rec.Stroke = blackBrush;
Rec.Fill = newBrush;
Canvas.SetTop(Rec, generateY(b.locationY));
Canvas.SetLeft(Rec, generateX(b.locationX));
TextBlock blockname = new TextBlock();
blockname.Text = b.blockText;
blockname.FontSize = 25;
canvas1.Children.Add(Rec);
canvas1.Children.Add(blockname);
Binding topbinding = new Binding("Top");
Binding leftbinding = new Binding("Left");
topbinding.Mode = BindingMode.OneWay;
leftbinding.Mode = BindingMode.OneWay;
topbinding.Source = Rec.GetValue(Canvas.TopProperty);
leftbinding.Source = Rec.GetValue(Canvas.LeftProperty);
blockname.SetBinding(Canvas.TopProperty, topbinding);
blockname.SetBinding(Canvas.LeftProperty, leftbinding);
Rec.MouseLeftButtonDown += new MouseButtonEventHandler(Handle_MouseDown);
Rec.MouseMove += new MouseEventHandler(Handle_MouseMove);
Rec.MouseLeftButtonUp += new MouseButtonEventHandler(Handle_MouseUp);
}
These rectangles are built from a block class
public class block
{
public double locationX { get; set; }
public double locationY { get; set; }
public Color blockColor { get; set; }
public string blockText { get; set; }
public block(double x, double y, Color c, string s)
{
this.locationX = x;
this.locationY = y;
this.blockColor = c;
this.blockText = s;
}
}
And my mouse event handlers:
bool isMouseCaptured;
double mouseVerticalPosition;
double mouseHorizontalPosition;
public void Handle_MouseDown(object sender, MouseEventArgs args)
{
Rectangle item = sender as Rectangle;
mouseVerticalPosition = args.GetPosition(null).Y;
mouseHorizontalPosition = args.GetPosition(null).X;
isMouseCaptured = true;
item.CaptureMouse();
}
public void Handle_MouseMove(object sender, MouseEventArgs args)
{
Rectangle item = sender as Rectangle;
if (isMouseCaptured)
{
// Calculate the current position of the object.
double deltaV = args.GetPosition(null).Y - mouseVerticalPosition;
double deltaH = args.GetPosition(null).X - mouseHorizontalPosition;
double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);
// Set new position of object.
item.SetValue(Canvas.TopProperty, newTop);
item.SetValue(Canvas.LeftProperty, newLeft);
// Update position global variables.
mouseVerticalPosition = args.GetPosition(null).Y;
mouseHorizontalPosition = args.GetPosition(null).X;
}
}
public void Handle_MouseUp(object sender, MouseEventArgs args)
{
Rectangle item = sender as Rectangle;
isMouseCaptured = false;
item.ReleaseMouseCapture();
mouseVerticalPosition = -1;
mouseHorizontalPosition = -1;
}
The text I am trying to move is called blockname in formatBox(). I have tried Binding as you can see here but I think there is a gap in my knowledge of an easier way to do this. Either way I would like the text to move when the block moves under it when the mouse event handlers are triggered. How do I get the text to move with it?
Since you have mousehandlers already you could just skip the binding and use code. (The binding wouldn't work as expected anyway: the text would have the same coordinates as the reactangle so it gets drawn over the top/left lines of the rectangle. This will look ugly and make the text hard to read, you need to offset the text so that it's inside the reactangle or outside). Basically what you would do is in MouseDown put a flag high to idicate the mouse was pressed, and record the point where the mouse is. Then in MouseMove you check the flag: if it is on, calculate the new position for your rectangle as it's currentposition + the distance moved from the point recorded in MouseDown. The position of the text would then be the new position + some offset.
btw I suggest to split methods like formatBox into multiple smaller methods and choose better names for your variables: it will make the code not only more readable, but also more maintainable.
edit
to figure out which rectangle to move, do a hit test on all your elements in the MouseDwon handler. Something like this:
Rectangle rectangleUnderMouse = null;
foreach( var rec in rectangles )
{
if( VisualTreeHelper.HitTest( rec, pointWhereMouseIs ) )
{
rectangleUnderMouse = rec;
break;
}
}
edit
sorry I didn't see you asked which textblock to move.. That is easier: you could keep a Dictionary<Rectangle,TextBlock> inside your main class:
public void formatBox(block b)
{
//...
myDictionary[ Rec ] = textblock;
}
public void Handle_MouseMove( object sender, MouseEventArgs args )
{
//...
textBlockForThisRect = myDictionary[ item ];
//move textBlockForThisRect
}

Categories