Drag & drop between Listbox items and chess board - c#

I am trying to find a way to Drag & drop between Listbox items and chess board using WPF. I have a listbox on the left and a chess board on the right. How can I drag an item then drag into one or more squares of the chess board. Then click to the square, some information about the items here will be shown. I appreciate it if someone can help me? Thanks to everyone.

I think that this helps you: http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/

Hi here is a way to get you in the right direction
http://johnnblade.wordpress.com/2012/06/12/drag-and-drop-grid-control-row-devexpress-wpf/
let me know may u have more questions

Here is wat i hv done ..but here i drag the files from desktop to my listbox
` public MainPage()
{
InitializeComponent();
CompositionTarget.Rendering +=new EventHandler(CompositionTarget_Rendering);
FileBoard.Drop += new DragEventHandler(FileBoard_Drop);
}
`
when you drag element
void FileBoard_Drop(object sender, DragEventArgs e)
{
if (e.Data != null)
{
FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
foreach (FileInfo fi in files)
{
_files.Enqueue(fi);
}
}
}
create a list DATAinGrid
using CompositionTargetRendering u can deque the files
private void CompositionTarget_Rendering(Object sender, EventArgs e)
{
if (_files.Count != 0)
{
// Create a photo
FileInfo fi = _files.Dequeue();
}
}
and then allocate the itemsource to ur board or chess box item...try modifying the code i think u will get it

This is old but I found a KISS solution to this.
Create your chess board grid using TextBlocks or images in a grid.
Create a model for the data to be passed.
in the xml do this:
<TextBlock x:Name="myname" x:Uid="myname" Grid.Row="0" Grid.Column="1" Margin="3" Text="{Binding myfield}" Style="{DynamicResource myStyle}" AllowDrop="True" Drop="Square_Drop"/>
<TextBlock x:Name="myname" x:Uid="myname" Grid.Row="1" Grid.Column="1" Margin="3" Text="{Binding myfield}" Style="{DynamicResource myStyle}" AllowDrop="True" Drop="Square_Drop"/>
//etc etc etc
<ListBox x:Name="myListBox" x:Uid="myListBox"
ItemContainerStyle="{DynamicResource myListBoxListItemStyle}" Margin="10"
DisplayMemberPath="myField"
PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown">
I would strongly recommend you use a resource for the styling of the TextBlock/Image squares. (one for white, one for black!)
Learn how here
Then in your c# behind you will need:
private void List_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (myListBox.SelectedItem != null)
{
ListBox parent = (ListBox)sender;
myModel data = parent.SelectedItem as myModel;
if (data != null)
{
DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
}
}
}
private void Square_Drop(object sender, DragEventArgs e)
{
MyModel data = e.Data.GetData(typeof(MyModel)) as MyModel;
TextBlock tb = sender as TextBlock;
tb.DataContext = data;
//Add any database update code here
refreshInterface();
}

Related

Drag & Drop from explorer to wpf element

Everything seems to be simple and there are quite a few tutorials, but I cannot transfer data (in my case, an image) to a wpf window element. I was able to implement the transfer of an image from one element to another. But when I capture an image (for example, a desktop), when I transfer it to the desired element, the transfer option does not even appear, only a crossed-out circle and does not work out more than one event associated with drop (as if AllowDrop = false)
My code:
XAML
<Image x:Name="mainContent" Grid.Column="1" Stretch="Fill" AllowDrop="True" Drop="MainContent_Drop" />
C#
private void SpImageLeft_MouseDown(object sender, MouseButtonEventArgs e)
{
Image image = sender as Image;
DragDrop.DoDragDrop(image, image, DragDropEffects.Copy);
}
private void MainContent_Drop(object sender, DragEventArgs e)
{
Image image = (Image)e.Data.GetData(typeof(Image));
mainContent.Source = image.Source;
}
I understand that when I take an image from explorer it will be different there, something like this, but it still does not even show that you can add an image
private void MainContent_Drop(object sender, DragEventArgs e)
{
string[] arr = (string[])e.Data.GetData(DataFormats.FileDrop);
mainContent.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(arr[0]);
}
The following worked for me as a Drop event handler for an Image control:
private void OnMainImageDrop(object sender, DragEventArgs e)
{
if (sender is Image image && e.Data.GetDataPresent(DataFormats.FileDrop))
{
if (e.Data.GetData(DataFormats.FileDrop) is string[] filePaths)
{
image.Source.Freeze();
string filePath = filePaths[0];
var uriSource = new Uri(filePath);
var imageSource = new BitmapImage(uriSource);
image.Source = imageSource;
}
}
}
I used a placeholder image to make sure the image had a size and served as a mouse hover surface.
XAML:
<Image x:Name="MainImage" Grid.Row="1"
Source="Images/DotNetLogo.png"
Stretch="Uniform"
AllowDrop="True" Drop="OnMainImageDrop"/>

c# - Find and modified image control by gridview selecteditem

I need to change the source of an Image control inside a gridview datatemplate when a click event is raised in uwp. When i click on a car image, this Image needs to be modified and displayed the brand logo. I succeed with that code:
<controls:AdaptiveGridView x:Name="AdaptiveGridViewControl"
animations:ReorderGridAnimation.Duration="350"
Margin="0,12,0,0"
ItemHeight="200"
DesiredWidth="200"
SelectionMode="Single"
IsItemClickEnabled="True"
ItemClick="GridView_ItemClick"
>
<controls:AdaptiveGridView.ItemTemplate>
<DataTemplate x:DataType="data:MyData">
<StackPanel Orientation="Horizontal">
<controls:ImageEx x:Name="ImageExControl"
MaxHeight="200"
IsCacheEnabled="True"
Source="{x:Bind carsPictures}"
Stretch="Fill"
PlaceholderSource="/Assets/placeholder_cover.jpg"
PlaceholderStretch="Uniform"/>
</StackPanel>
</DataTemplate>
</controls:AdaptiveGridView.ItemTemplate>
</controls:AdaptiveGridView>
Thanks to that post : How to access a Control inside the data template in C# Metro UI in the code behind,
i can use FindChildControl(DependencyObject control, string ctrlName) method.
In code behind:
private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
var newData = (MyData)e.ClickedItem;
ImageEx ex = FindChildControl<ImageEx>(this, "ImageExControl") as ImageEx;
ex.Source = newData.brandLogo;
}
The problem is this gridview contains 30 cars picture and only the first Image control is modified when a click event is raised. I don't know how to use the AdaptiveGridView.SelectedItem to change the clicked Image control.
You need to Get GridViewItem that has been Clicked so that you can change the image of the Clicked Item. Change your ItemClick Event to something like below.
private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
GridViewItem item = myGridView.ContainerFromItem(e.ClickedItem) as GridViewItem;
MyData newData = (MyData)e.ClickedItem;
ImageEx ex = FindChildControl<ImageEx>(item, "ImageExControl") as ImageEx;
ex.Source = newData.brandLogo;
}
Hope This Helps.

How to Get Tap Event from User Control in Page

Hopefully the question makes sense. What I would like to do is place an Ellipse (or styled button to look like an Ellipse with an icon inside in a user control that is dynamically populated in my code behind, and then be able to determine when the Ellipse was tapped on the user control and perform a separate action than when the user control is tapped. The sample I'm using actually comes from a Nokia Imaging SDK sample with a few tweaks.
PhotoThumbnail.xaml //The UserControl
<Ellipse Grid.Row="0" Grid.Column="1" Stroke="LightGray" StrokeThickness="3"
VerticalAlignment="Top" HorizontalAlignment="Right" Width="50" Height="50" Margin="7"/>
PhotoThumbnail.xaml.cs
public event PropertyChangedEventHandler PropertyChanged;
public PhotoThumbnail()
{
InitializeComponent();
DataContext = this;
}
Page.xaml.cs
//Creae PhotoThumbnail
PhotoThumbnail photoThumbnail = new PhotoThumbnail()
{
..
};
photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) =>
{
// do something
};
panel.Children.Add(photoThumbnail);
}
}
}
}
The photoThumbnail.Tap event above performs an action, but how can I determine if the user tapped the Ellipse on the PhotoThumbnail UserControl as opposed to the control itself?
I just added the following in Page.xaml.cs and named the Ellipse in the User Control x:Name="EditableEllipse"
photoThumbnail.EditableEllipse.Tap += (object sender, System.Windows.Input.GestureEventArgs e) =>
{
if (sender != null)
{
.. do something ..
}
};

What is the correct way to code the nested methods?

I have created a registration form in silverlight 4, where i have a large number of text-boxes, in front of each text box i have placed a text-block as a required field validator, when any of the textbox left empty while loosing focus, the textblock placed in front of it must become red.
textboxes named textbox1, textbox2 ... and so as the textblocks
the problem is, i do not want code the specific method for each specific textbox, all i want to do is to complete such in just two three methods
here i did some coding which doesn't seems to be correct
private void textBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox) sender;
if (textbox.Text == "")
{
var textblock = "textblock" + textBox.Name.Remove(0,7);
TextblockColorChange(textblock);
}
}
private void TextblockColorChange(object sender)
{
var textblock = (TextBlock) sender;
textblock.Foreground= new SolidColorBrush(Colors.Red);
}
please suggest some better way to do so..
I'd create a UserControl that contains the TextBlock and the TextBox and use this UserControl everywhere you currently have the TextBlock and TextBox combination. Then this Usercontrol would have the LostFocus logic inside it and update the TextBlock appropriately. This prevents the need to figure out the right name of the control to update.
you need something like this,
XAML part:
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Horizontal" Height="25">
<TextBox Width="150" LostFocus="TextBox_LostFocus"/>
<TextBlock Text="*" Foreground="#FF0000" VerticalAlignment="Center" Margin="10,0,0,0" Visibility="Collapsed"/>
</StackPanel>
</Grid>
C# Part:
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textbox = sender as TextBox;
if(textbox == null) return;
var stackPanel = textbox.Parent as StackPanel;
if(stackPanel == null) return;
var textBlock = stackPanel.Children.Where(a => a is TextBlock).FirstOrDefault();
if (textBlock == null) return;
if (string.IsNullOrEmpty(textbox.Text)) textBlock.Visibility = Visibility.Visible;
else textBlock.Visibility = Visibility.Collapsed;
}
Whilst I actually prefer Bills approach (although I'd be inclined to use a Templated Control) here is another alternative which is quite fun. In your xaml use this sort of markup:-
<TextBlock Text="Enter Value 1" Foreground="{Binding Tag, ElementName=textBox1, TargetNullValue=Black}" />
<TextBox x:Name="textBox1" LostFocus="txt_LostFocus" />
Your common txt_LostFocus can look like this:-
private void txt_LostFocus(object sender, RoutedEventArgs e)
{
TextBox txt = ((TextBox)sender);
if (String.IsNullOrEmpty(txt.Text))
{
txt.Tag = new SolidColorBrush(Colors.Red);
}
else
{
txt.Tag = null;
}
}
var textblock = "textblock" + textBox.Name.Remove(0,7);
TextblockColorChange(textblock);
This code above will just send a string to TextblockColorChange()
You don't show any other code, but I'm guessing you want to do a FindControl or FindControl like search on that string before passing the result to your code.

WPF layer event separation

I have the highest layer called "canvas" which is used to display picture. Then, I'm trying to use event menuCanvas_touchDown to lowest layer called "menuCanvas" which show my workspace menu. However, when I touch the picture, it go to menuCanvas_touchDown. It should be found at the menuCanvas layer.
<Canvas x:Name="menuCanvas"
TouchDown="menuCanvas_TouchDown" TouchUp="menuCanvas_TouchUp"
TouchMove="menuCanvas_TouchMove" TouchLeave="menuCanvas_TouchLeave"
TouchEnter="menuCanvas_TouchEnter"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Background="Transparent"
IsManipulationEnabled="True">
<Canvas x:Name="drawCanvas"
TouchDown="drawCanvas_TouchDown" TouchUp="drawCanvas_TouchUp"
TouchMove="drawCanvas_TouchMove" TouchLeave="drawCanvas_TouchLeave"
TouchEnter="drawCanvas_TouchEnter"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Background="Transparent"
IsManipulationEnabled="True">
<Canvas x:Name="canvas"></Canvas>
</Canvas>
</Canvas>
I want to touch picture and nothing happen to menuCanvas_touchDown event.
How do I solve this problem? I'm trying to use e.handle, but it break the manipulation of the picture.
Thanks
Edit:
There are drawCanvas_TouchDown and drawCanvas_TouchUp code.
private void drawCanvas_TouchDown(object sender, TouchEventArgs e)
{
if (state == (int)STATE.Pen)
{
if (_activeStrokes.TryGetValue(e.TouchDevice.Id, out stroke))
{
FinishStroke(stroke);
return;
}
// Create new stroke, add point and assign a color to it.
Stroke newStroke = new Stroke();
newStroke.Color = _touchColor.GetColor();
newStroke.Id = e.TouchDevice.Id;
// Add new stroke to the collection of strokes in drawing.
_activeStrokes[newStroke.Id] = newStroke;
}
}private void drawCanvas_TouchUp(object sender, TouchEventArgs e)
{
// Find the stroke in the collection of the strokes in drawing.
if (state == (int)STATE.Pen)
{
if (_activeStrokes.TryGetValue(e.TouchDevice.Id, out stroke))
{
FinishStroke(stroke);
}
}
}
Have you try to use e.OriginalSource? You can check source of event.
if(e.OriginalSource == menuCanvas)
{
//Your code
}

Categories

Resources