C# DataGridView - c#

I have been tasked with creating a somewhat hierarchical datagridview for my company. I heavily modified one from Syed Shanu that is posted here https://www.codeproject.com/Articles/848637/Nested-DataGridView-in-windows-forms-csharp. I'm almost done (data loads properly, etc.), however I cannot for the life of me figure out how to get the detail grid to move when I scroll. It's a drawn on rectangle and I'm looking for a way to somehow bind it to the master grid so it scrolls up and down with the regular grid. Any help would be appreciated. Here is the code that draws the rectangle:
private void masterDGVs_CellContentClick_Event(object sender, DataGridViewCellEventArgs e)
{
DataGridViewImageColumn cols = (DataGridViewImageColumn)MasterDGVs.Columns[0];
MasterDGVs.Rows[e.RowIndex].Cells[0].Value = Image.FromFile(#"expand.png");
if (e.ColumnIndex == gridColumnIndex)
{
if (ImageName == #"expand.png")
{
DetailDGVs.Visible = true;
ImageName = #"toggle.png";
MasterDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Image.FromFile(ImageName);
String FilterExpression = MasterDGVs.Rows[e.RowIndex].Cells[FilterColumnName].Value.ToString();
MasterDGVs.Controls.Add(DetailDGVs);
Rectangle DGVRectangle = MasterDGVs.GetCellDisplayRectangle(1, e.RowIndex, true);
DetailDGVs.Size = new Size(MasterDGVs.Width - 48, DetailDGVs.PreferredSize.Height - 16);
DetailDGVs.Location = new Point(DGVRectangle.X, DGVRectangle.Y + 20);
DataView detailView = new DataView(DetailGridDT);
detailView.RowFilter = FilterColumnName + " = '" + FilterExpression + "'";
foreach (DataGridViewRow row in DetailDGVs.Rows)
{
if (row.Cells[5].Value.ToString() == "Error")
{
row.Cells[5].Style.ForeColor = Color.DarkRed;
}
else if (row.Cells[5].Value.ToString() == "Processed and Complete")
{
row.Cells[5].Style.ForeColor = Color.Green;
}
else
{
row.Cells[5].Style.ForeColor = Color.Yellow;
}
}
}
else
{
ImageName = #"expand.png";
MasterDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Image.FromFile(ImageName);
DetailDGVs.Visible = false;
}
}
else
{
DetailDGVs.Visible = false;
}
}
I have sort of working by adding:
MasterDGVs.MouseWheel += new MouseEventHandler(DetailDGV_Scroll);
DetailDGVs.MouseWheel += new MouseEventHandler(MasterDGV_Scroll);
and
private void DetailDGV_Scroll(object sender, MouseEventArgs e)
{
int scale = e.Delta * SystemInformation.MouseWheelScrollLines / 5;
DetailDGVs.Top = DetailDGVs.Top + scale;
}
private void MasterDGV_Scroll(object sender, MouseEventArgs e)
{
int scale = e.Delta * SystemInformation.MouseWheelScrollDelta / 5;
MasterDGVs.Top = MasterDGVs.Top - scale;
}

Related

How to draw moving axis table

I'm trying to draw an axis table (x-y) in WPF from code-behind; and I want to give it drag and drop option which can see more of the axis table.
I had created static axis but I don't know how to create a dynamic one?
Can anybody help me with this stuff ?
Thanks.
for (int i = 10; i < 400; i+=10)
{
Line a = new Line();
a.X1 = 0;
a.Y1 = i;
a.X2 = canGraph.Width;
a.Y2 = a.Y1;
a.Stroke = System.Windows.Media.Brushes.Black;
a.StrokeThickness = 0.5;
canGraph.Children.Add(a);
Line b = new Line();
b.X1 = i;
b.Y1 = 0;
b.X2 = i;
b.Y2 = canGraph.Height;
b.Stroke = System.Windows.Media.Brushes.Black;
b.StrokeThickness = 0.5;
canGraph.Children.Add(b);
if (i % 50 == 0)
{
a.StrokeThickness = 1;
b.StrokeThickness = 1;
}
if (i == 200)
{
a.StrokeThickness = 2;
b.StrokeThickness = 2;
}
}
This should get you started. Add event handler(s) to your main axis and canGraph -
...
if (i == 200)
{
a.StrokeThickness = 2;
b.StrokeThickness = 2;
a.MouseLeftButtonDown += A_MouseLeftButtonDown;
}
}
canGraph.MouseLeftButtonUp += CanGraph_MouseLeftButtonUp;
canGraph.MouseMove += CanGraph_MouseMove;
Add following methods -
Line _selectedAxis = null;
private void CanGraph_MouseMove(object sender, MouseEventArgs e)
{
if (_selectedAxis != null)
{
var line = _selectedAxis;
var pos = e.GetPosition(line);
textBlock.Text = $"({pos.X}, {pos.Y})";
line.Y1 = pos.Y;
line.Y2 = pos.Y;
}
}
private void CanGraph_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
_selectedAxis = null;
}
private void A_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var line = sender as Line;
_selectedAxis = line;
}
Now hold you main horizontal axis and drag it.
You can do the same for vertical axis as well.
For Zooming
Initialize canGraph.RenderTransform with ScaleTransform and subscribe to MouseWheel event. Note RenderTransformOrigin is set to (0.5, 0.5) to zoom from center instead of top left (default) -
canGraph.RenderTransformOrigin = new Point(0.5, 0.5);
canGraph.RenderTransform = new ScaleTransform();
canGraph.MouseWheel += CanGraph_MouseWheel;
And the function -
private void CanGraph_MouseWheel(object sender, MouseWheelEventArgs e)
{
var transform = canGraph.RenderTransform as ScaleTransform;
var factor = transform.ScaleX;
factor += (e.Delta > 0 ? 1 : (factor == 1 ? 0 : -1));
transform.ScaleX = factor;
transform.ScaleY = factor;
}
I'm guessing you have added Line type object to draw axes, then gave it to window content.
Then just add events, like MouseLeftButtonDown event, or MouseMove event.Add appropriate methods.
Change your object positions on MouseMove event, like:
(For a certain line)
private void MouseMoveMethod(object sender, MouseEventArgs e)
{
var obj = sender as Line;
obj.X1 = e.GetPosition(this).X; //Line start x coordinate
obj.Y1 = e.GetPosition(this).Y; //Line start y coordinate
...
}

Why the event "gridControl1_DragDrop" and "gridControl1_DragOver" does not work

DevExpress 17.2.7
I try to make moving one row inside the grid
The element "User Control" is placed "gridControl1".
The code contains the events:
- "gridView1_MouseDown";
- "gridView1_MouseMove";
- "gridControl1_DragOver";
- "gridControl1_DragDrop".
Events "gridView1_MouseDown", "gridView1_MouseMove" work.
Events "gridControl1_DragOver", "gridControl1_DragDrop" do not work.
In other words, they do not even react.
How to make the "gridControl1_DragOver", "gridControl1_DragDrop" events work?
public partial class Frm10UC : UserControl
{
#region *** Переменные
// *** Переменные
ConectDB conectDB;
#region Перетаскивание
#region *** Сортировка
const string OrderFieldName = "sorting";
#endregion **
#endregion
#endregion *** Переменные
public Frm10UC()
{
InitializeComponent();
}
private void Frm10UC_Load(object sender, EventArgs e)
{
// Подключение к БД
// conectDB = new ConectDB(Convert.ToInt32(aIncement));
conectDB = new ConectDB();
conectDB.connect();
// gridControl. Заполнение данными
gridControl1.DataSource = conectDB.dt;
gridView1.BestFitColumns();
// Строка. Добавить "Новую запись"
// Отображение строки нового элемента для добавления строк в представление.
gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top; // Available modes: Top, Bottom, None (// Доступные режимы: сверху, снизу, нет)
// Сортировка
// SortData();
#region *** Сортировка
gridView1.PopulateColumns(); // Создает столбцы сетки/поля карты для полей в связанном источнике данных View.
gridView1.Columns[OrderFieldName].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending; //Сортировка. "Ascending" - по возрастанию
gridView1.OptionsCustomization.AllowSort = false; // Получает или задает значение, определяющее, могут ли конечные пользователи применять сортировку данных .
gridView1.OptionsView.ShowGroupPanel = false; // Возвращает или задает значение, определяющее, является ли панель группы видимой.
#endregion *** Сортировка
}
#region *** События
GridHitInfo downHitInfo = null; // Содержит информацию о конкретной точке в виде сетки .
// https://documentation.devexpress.com/WindowsForms/DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo.members
private void gridView1_MouseDown(object sender, MouseEventArgs e)
{
GridView view = sender as GridView;
downHitInfo = null;
GridHitInfo hitInfo = view.CalcHitInfo(new Point(e.X, e.Y));
if (Control.ModifierKeys != Keys.None)
return;
if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.RowHandle != GridControl.NewItemRowHandle)
downHitInfo = hitInfo;
}
private void gridView1_MouseMove(object sender, MouseEventArgs e)
{
GridView view = sender as GridView;
if (e.Button == MouseButtons.Left && downHitInfo != null)
{
Size dragSize = SystemInformation.DragSize;
Rectangle dragRect = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2,
downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
if (!dragRect.Contains(new Point(e.X, e.Y)))
{
view.GridControl.DoDragDrop(downHitInfo, DragDropEffects.All);
downHitInfo = null;
}
}
}
private void gridControl1_DragOver(object sender, DragEventArgs e) // когда объект перетаскивается по границам элемента управления;
{
if (e.Data.GetDataPresent(typeof(GridHitInfo)))
{
GridHitInfo downHitInfo = e.Data.GetData(typeof(GridHitInfo)) as GridHitInfo;
if (downHitInfo == null)
return;
GridControl grid = sender as GridControl;
GridView view = grid.MainView as GridView;
GridHitInfo hitInfo = view.CalcHitInfo(grid.PointToClient(new Point(e.X, e.Y)));
if (hitInfo.InRow && hitInfo.RowHandle != downHitInfo.RowHandle && hitInfo.RowHandle != GridControl.NewItemRowHandle)
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
}
private void gridControl1_DragDrop(object sender, DragEventArgs e) //когда операция перетаскивания завершена;
{
GridControl grid = sender as GridControl;
GridView view = grid.MainView as GridView;
GridHitInfo srcHitInfo = e.Data.GetData(typeof(GridHitInfo)) as GridHitInfo;
GridHitInfo hitInfo = view.CalcHitInfo(grid.PointToClient(new Point(e.X, e.Y)));
int sourceRow = srcHitInfo.RowHandle;
int targetRow = hitInfo.RowHandle;
MoveRow(sourceRow, targetRow);
}
private void MoveRow(int sourceRow, int targetRow)
{
if (sourceRow == targetRow)
return;
GridView view = gridView1;
DataRow row0 = null;
DataRow row1 = null;
DataRow row2 = null;
decimal val1 = 0;
decimal val2 = 0;
if (targetRow == sourceRow + 1)
{
row1 = view.GetDataRow(sourceRow);
row2 = view.GetDataRow(targetRow);
val1 = (decimal)row1[OrderFieldName];
val2 = (decimal)row2[OrderFieldName];
row1[OrderFieldName] = val2;
row2[OrderFieldName] = val1;
view.FocusedRowHandle = sourceRow + 1;
return;
}
if (sourceRow == targetRow + 1)
{
row1 = view.GetDataRow(sourceRow);
row2 = view.GetDataRow(targetRow);
val1 = (decimal)row1[OrderFieldName];
val2 = (decimal)row2[OrderFieldName];
row1[OrderFieldName] = val2;
row2[OrderFieldName] = val1;
view.FocusedRowHandle = sourceRow - 1;
return;
}
row0 = view.GetDataRow(targetRow - 1);
row1 = view.GetDataRow(targetRow);
row2 = view.GetDataRow(targetRow + 1);
DataRow dragRow = view.GetDataRow(sourceRow);
val1 = (decimal)row1[OrderFieldName];
if (row2 == null)
dragRow[OrderFieldName] = val1 + 1;
else
{
val2 = (decimal)row2[OrderFieldName];
if (row0 == null)
dragRow[OrderFieldName] = val1 - 1;
else
dragRow[OrderFieldName] = (val1 + val2) / 2;
}
}
#endregion *** События
}
Have you set the AllowDrop property of the GridView control to true?
Without this set the events will not fire.

Selected Filename not showing in Label from one Form to another C#

I am working modifying an application that will be an utility. The application is designed so far to load pictures from any folder and show them in thumbnails, then the user should be able to select those that will want to save in a database. The thumbnails consists of an ImageViewer form that will load each image. Thus, in the ImageViewer form there is a textbox and a checkbox. Each of them will be generated dynamically as many pictures are loaded (see the image below). The problem is that when clicking the checkbox it should show the name listed above the picture (thumbnail textbox) of the file in a label (it can be a label or textbox). Any time when the user clicks the checkbox will see a message saying: 'Added anyImage.jpg' or when deselecting the checkbox will say 'Removed anyImage.jpg'. It is not showing the text in the label. I have the following code.
This code is to load the main form:
public MainForm()
{
InitializeComponent();
Login loginSystem = new Login();
lbHowMany.Visible = false;
lbHowMany.Text = "Images";
lbNumberOfFiles.Visible = false;
btnEnableViewer.Text = "Disable Viewer";
this.buttonCancel.Enabled = false;
//stripSelectedFile.Text = "";
m_ImageDialog = new ImageDialog();
m_AddImageDelegate = new DelegateAddImage(this.AddImage);
m_Controller = new ThumbnailController();
m_Controller.OnStart += new ThumbnailControllerEventHandler(m_Controller_OnStart);
m_Controller.OnAdd += new ThumbnailControllerEventHandler(m_Controller_OnAdd);
m_Controller.OnEnd += new ThumbnailControllerEventHandler(m_Controller_OnEnd);
if (ImageViewer.sendSelectedFile != null)
{
stripSelectedFile.Text = ImageViewer.sendSelectedFile.ToString();
txInformation.Text = ImageViewer.sendSelectedFile.ToString();
}
}
This other code is from the ImageViewer form checkbox:
public void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (cboxToSave.Checked == true)
{
sendSelectedFile = "Added: " + txFileName.Text;
}
else
{
{
sendSelectedFile = "Removed: " + txFileName.Text;
}
}
}
This is the variable declared in the class that will send the selected file name to the main form: public static string sendSelectedFile;
ImageViewer Code:
public partial class ImageViewer : UserControl
{
private Image m_Image;
private string m_ImageLocation;
private bool m_IsThumbnail;
private bool m_IsActive;
public static string sendSelectedFile;
public ImageViewer()
{
m_IsThumbnail = false;
m_IsActive = false;
InitializeComponent();
}
public Image Image
{
set
{
m_Image = value;
}
get
{
return m_Image;
}
}
public string ImageLocation
{
set
{
m_ImageLocation = value;
}
get
{
return m_ImageLocation;
}
}
public bool IsActive
{
set
{
m_IsActive = value;
this.Invalidate();
}
get
{
return m_IsActive;
}
}
public bool IsThumbnail
{
set
{
m_IsThumbnail = value;
}
get
{
return m_IsThumbnail;
}
}
public void ImageSizeChanged(object sender, ThumbnailImageEventArgs e)
{
this.Width = e.Size;
this.Height = e.Size;
this.Invalidate();
}
public void LoadImage(string imageFilename, int width, int height)
{
Image tempImage = Image.FromFile(imageFilename);
m_ImageLocation = imageFilename;
//gets the name of the file from the location
txFileName.Text = Path.GetFileNameWithoutExtension(imageFilename);
int dw = tempImage.Width;
int dh = tempImage.Height;
int tw = width;
int th = height;
double zw = (tw / (double)dw);
double zh = (th / (double)dh);
double z = (zw <= zh) ? zw : zh;
dw = (int)(dw * z);
dh = (int)(dh * z);
m_Image = new Bitmap(dw, dh);
Graphics g = Graphics.FromImage(m_Image);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(tempImage, 0, 0, dw, dh);
g.Dispose();
tempImage.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
if (g == null) return;
if (m_Image == null) return;
int dw = m_Image.Width;
int dh = m_Image.Height;
int tw = this.Width - 8; // remove border, 4*4
int th = this.Height - 8; // remove border, 4*4
double zw = (tw / (double)dw);
double zh = (th / (double)dh);
double z = (zw <= zh) ? zw : zh;
dw = (int)(dw * z);
dh = (int)(dh * z);
int dl = 4 + (tw - dw) / 2; // add border 2*2
int dt = 4 + (th - dh) / 2; // add border 2*2
g.DrawRectangle(new Pen(Color.Yellow), dl, dt, dw, dh);
if (m_IsThumbnail)
for (int j = 0; j < 3; j++)
{
//draws and color the horizontal line in the miniature
g.DrawLine(new Pen(Color.LightSalmon),
new Point(dl + 3, dt + dh + 1 + j),
new Point(dl + dw + 3, dt + dh + 1 + j));
//draws and color the vertical right line in the miniature
g.DrawLine(new Pen(Color.LightGreen),
new Point(dl + dw + 1 + j, dt + 3),
new Point(dl + dw + 1 + j, dt + dh + 3));
}
g.DrawImage(m_Image, dl, dt, dw, dh);
if (m_IsActive)
{
//draws the rectangle inside and gives it color
g.DrawRectangle(new Pen(Color.MediumTurquoise, 1), dl, dt, dw, dh);
//draws the rectangle outside and gives it color
g.DrawRectangle(new Pen(Color.RosyBrown, 2), dl - 2, dt - 2, dw + 4, dh + 4);
}
}
private void OnResize(object sender, EventArgs e)
{
this.Invalidate();
}
public void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (cboxToSave.Checked == true)
{
sendSelectedFile = "Added: " + txFileName.Text;
}
else
{
{
sendSelectedFile = "Removed: " + txFileName.Text;
}
}
}
}
Code in the MainForm that adds the images in the flowLayoutPanelMain
delegate void DelegateAddImage(string imageFilename);
private DelegateAddImage m_AddImageDelegate;
private void AddImage(string imageFilename)
{
try
{
// thread safe
if (this.InvokeRequired)
{
this.Invoke(m_AddImageDelegate, imageFilename);
}
else
{
int size = ImageSize;
lbNumberOfFiles.Visible = true;
lbHowMany.Visible = true;
ImageViewer imageViewer = new ImageViewer();
imageViewer.Dock = DockStyle.Bottom;
imageViewer.LoadImage(imageFilename, 256, 256);
imageViewer.Width = size;
imageViewer.Height = size;
imageViewer.IsThumbnail = true;
imageViewer.MouseClick += new MouseEventHandler(imageViewer_MouseClick);
txInformation.Text = imageFilename;
SetProgressBar();
counter++;
lbHowMany.Text = "Images";
lbNumberOfFiles.Text = counter.ToString();
this.OnImageSizeChanged += new ThumbnailImageEventHandler(imageViewer.ImageSizeChanged);
//passes the pictures to the main picture container
this.flowLayoutPanelMain.Controls.Add(imageViewer);
}
}
catch (Exception e)
{
MessageBox.Show("An error has ocurred. Error: " + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here's a quick example of the ImageViewer Form raising a custom event whenever the checkbox is changed:
public partial class ImageViewer : Form
{
public ImageViewer()
{
InitializeComponent();
}
public delegate void dlgImageChecked(ImageViewer sender, string message);
public event dlgImageChecked ImageChecked;
private void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (ImageChecked != null)
{
ImageChecked(this, (cboxToSave.Checked ? "Added: " : "Removed: ") + txFileName.Text);
}
}
}
Now, when you create instances of ImageViewer, you need to wire up that event...something like:
// ... in your MainForm class ...
private void button1_Click(object sender, EventArgs e)
{
// when you create your instances of ImageViewer, wire up their ImageChecked() event:
ImageViewer iv = new ImageViewer();
iv.ImageChecked += Iv_ImageChecked;
}
private void Iv_ImageChecked(ImageViewer sender, string message)
{
ImageViewer iv = (ImageViewer)sender; // if you need to reference it for other reasons ...
stripSelectedFile.Text = message;
txInformation.Text = message;
}
Your original post didn't show the creation of your ImageViewer instances so you'll need to incorporate the above somehow into your code.

Drawing background image into form overflow client area

I have a problem with drawing image on form background. I have a form where there are inserted both scrollbars (H and V). Because I need to be able display image in original size I use them for scrolling it but when I scroll to maximum right or bottom on both sides missing 7 pixels which are hidden under scrollbars. There is sample code:
private int PosX, PosY;
this.Map = new Bitmap(TestLines.Properties.Resources.mapa);
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
if (this.Map != null)
{
e.Graphics.DrawImageUnscaled(Map, new Point(this.PosX, this.PosY));
int MapResX = (int)((float)this.Map.Width / this.Map.HorizontalResolution * e.Graphics.DpiX);
int MapResY = (int)((float)this.Map.Height / this.Map.VerticalResolution * e.Graphics.DpiY);
if (MapResX > this.ClientSize.Width && MapResY > this.ClientSize.Height - this.toolStrip1.Height)
{
hScrollBar1.Minimum = 0;
hScrollBar1.Maximum = MapResX - this.ClientSize.Width + vScrollBar1.Width;
hScrollBar1.Visible = true;
vScrollBar1.Minimum = 0;
vScrollBar1.Maximum = MapResY - this.ClientSize.Height + toolStrip1.Height + hScrollBar1.Height;
vScrollBar1.Visible = true;
}
else if (MapResX > this.ClientSize.Width)
{
hScrollBar1.Minimum = 0;
hScrollBar1.Maximum = MapResX - this.ClientSize.Width;
hScrollBar1.Visible = true;
vScrollBar1.Visible = false;
}
else if (MapResY > this.ClientSize.Height - this.toolStrip1.Height)
{
vScrollBar1.Minimum = 0;
vScrollBar1.Maximum = MapResY - this.ClientSize.Height + toolStrip1.Height;
vScrollBar1.Visible = true;
hScrollBar1.Visible = false;
}
else
{
hScrollBar1.Visible = false;
vScrollBar1.Visible = false;
}
}
}
Note that there is also a toolstrip where i do not draw. And then simple scrollbars actions:
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
this.PosX = -e.NewValue;
this.Invalidate(false);
this.Update();
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
this.PosY = toolStrip1.Height -e.NewValue;
this.Invalidate(false);
this.Update();
}
Can you describe me why this happens ?
This is just not the right way to go about it. Create your own control instead, using Panel as the base class so you get the scrolling for free. Add a new class to your project and paste the code shown below. Compile. Drop it from the top of the toolbox onto your form, you probably want to set its Dock property to Fill. Assign the Map property, either with the designer or in your code.
using System;
using System.Drawing;
using System.Windows.Forms;
class MapPanel : Panel {
public MapPanel() {
this.DoubleBuffered = true;
this.ResizeRedraw = true;
}
private Image map;
public Image Map {
get { return map; }
set {
map = value;
this.AutoScrollMinSize = value == null ? Size.Empty : value.Size;
this.Invalidate();
}
}
protected override void OnPaintBackground(PaintEventArgs e) {
base.OnPaintBackground(e);
if (map != null) {
e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
e.Graphics.DrawImage(map, 0, 0);
}
}
}

Drag and Drop dynamically generated images [C#/Windows Store App]

i have dynamically generated images. if i click last added image it dragging normally, but when i click to other image and tried to drag it, last added image dragging again.
here is my codes
void setDynamicImages()
{
for (int i = 0; i < 10; i++)
{
RectMeyve = new Rectangle();
IMG_meyve = new Image();
IMG_meyve.Height = 36 * ratioHeight;
IMG_meyve.Width = 51 * ratioWidth;
randMeyveCesit = Rand.Next(5);
IMG_meyve.Source = new BitmapImage(new Uri("ms-appx:///Assets/Sayfa10/dusen_meyveler/cilek_0" + (randMeyveCesit + 1) + ".png"));
IMG_meyve.Tag =randMeyveTur;
pressedIMGTag =randMeyveTur;
RectMeyve.Fill = new SolidColorBrush(Colors.Aqua);
RectMeyve.Height = IMG_meyve.ActualHeight;
RectMeyve.Width = IMG_meyve.Width;
Canvas.SetLeft(RectMeyve, Canvas.GetLeft(IMG_meyve));
Canvas.SetTop(RectMeyve, Canvas.GetTop(IMG_meyve));
RectMeyve.Opacity = 0.6;
RectMeyve.IsHitTestVisible = false;
IMG_meyve.ActualWidth, IMG_meyve.ActualHeight);
this.canvasMeyveleriSayalim.Children.Add(IMG_meyve);
this.canvasMeyveleriSayalim.Children.Add(RectMeyve);
IMG_meyve.PointerPressed += IMG_meyve_PointerPressed;
IMG_meyve.PointerReleased += IMG_meyve_PointerReleased;
}
}
private void IMG_meyve_PointerPressed(object sender, PointerRoutedEventArgs e)
{
isHoldMeyve = true;
positionWithinImage = e.GetCurrentPoint(sender as Image).Position;
meyveX = e.GetCurrentPoint(IMG_meyve).Position.X;
meyveY = e.GetCurrentPoint(IMG_meyve).Position.Y;
}
private void canvasSayfa10_PointerMoved(object sender, PointerRoutedEventArgs e)
{
if (isHoldMeyve)
{
if (Convert.ToInt32(IMG_meyve.Tag) == pressedIMGTag) //this part useless
{
PointerPoint pt1 = e.GetCurrentPoint(canvasMeyveleriSayalim);
Canvas.SetLeft(IMG_meyve, pt1.Position.X - meyveX);
Canvas.SetTop(IMG_meyve, pt1.Position.Y - meyveY);
}
}
}
sorry for my english.
where is my mistake.

Categories