I'm trying to upload images in Xamarin to Server via API.
.xaml
<Grid x:Name="pickimg" Grid.Row="0" Grid.Column="1" HorizontalOptions="End" VerticalOptions="Center">
<StackLayout Orientation="Horizontal">
<Image Margin="0">
<Image.Source>
<FontImageSource Color="#ddd" Size="22" FontFamily="MaterIcon" Glyph="{x:Static local:FontIconsClass.Camera}"/>
</Image.Source>
</Image>
</StackLayout>
<Grid.GestureRecognizers>
<TapGestureRecognizer Tapped="pickimg_Tapped" />
</Grid.GestureRecognizers>
</Grid>
<StackLayout HorizontalOptions="FillAndExpand">
<StackLayout x:Name="listImg" Orientation="Horizontal">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Frame HasShadow="False" Padding="0" IsClippedToBounds="True" CornerRadius="4">
<Image HeightRequest="70" WidthRequest="70" Aspect="AspectFill" Source="{Binding .}"/>
</Frame>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
.xaml.cs
This is how I display the list of selected photos:
async void pickimg_Tapped(System.Object sender, EventArgs e)
{
var pickResult = await MediaGallery.PickAsync(5, MediaFileType.Image);
if(pickResult?.Files == null)
{
return;
}
else
{
var imgList = new List<ImageSource>();
foreach (var img in pickResult?.Files)
{
var stream = await img.OpenReadAsync();
imgList.Add(ImageSource.FromStream(() => stream));
}
BindableLayout.SetItemsSource(listImg, imgList);
}
}
Everything seems fine. And I have 1 button to post the image to the Server:
private async void bt_addfeed_Clicked(object sender, EventArgs e)
{
var getResult = listImg;//How can I check and get the list of images in listImg?
if(getResult == null)
{
return;
}
else
{
var content = new MultipartFormDataContent();
content.Add(new StreamContent(await getResult.OpenReadAsync()), "file", getResult.FileName);
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("", content);......
}
}
How can I check and get the list of images in listImg? Please solutions, Thanks
Update...
List<ImageSource> imgList = new List<ImageSource>();
async void pickimg_Tapped(System.Object sender, EventArgs e)
{
var pickResult = await MediaGallery.PickAsync(5, MediaFileType.Image);
if(pickResult?.Files == null)
{
return;
}
else
{
foreach (var img in pickResult?.Files)
{
var stream = await img.OpenReadAsync();
imgList.Add(ImageSource.FromStream(() => stream));
}
BindableLayout.SetItemsSource(listImg, imgList);
}
}
private async void bt_addfeed_Clicked(object sender, EventArgs e)
{
var getResult = imgList;
if(getResult == null)
{
return;
}
else
{
var content = new MultipartFormDataContent();
content.Add(new StreamContent(await getResult.OpenReadAsync()), "file", getResult.FileName);
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("", content);......
}
}
How can getResult get .FileName and .OpenReadAsync()?
content.Add(new StreamContent(await getResult.OpenReadAsync()), "file", getResult.FileName);
you are declaring imgList as a local variable, so it only has scope inside the method where you declare it
var imgList = new List<ImageSource>();
instead, declare it as a class level variable so it will be accessible throughout the page
// do this inside the class body, but NOT within a specific method
List<ImageSource> imgList = new List<ImageSource>();
Ok I am using Lockito from the app store andriod to mock my location and I am getting the first long and lat but its not updating as it should I am storing the location in a list
This function here locationObtained does not appear to be getting called more than once.
I am using a real device for testing and have granted pemission to location.
private async Task<int> StartGps()
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
await DisplayAlert("Need location", "Gunna need that location", "OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
status = results[Permission.Location];
}
ILocation loc = DependencyService.Get<ILocation>();
loc.locationObtained += (object ss, ILocationEventArgs ee) =>
{
lat = ee.lat;
lng = ee.lng;
lbllat.Text = ee.lat.ToString();
lbllong.Text = ee.lng.ToString();
Position position = new Position(lat, lng);
postionsList.Add(position);
};
listPostions.ItemsSource = postionsList;
loc.ObtainMyLocation();
return 1;
}
In My Listview I have the following.
<ListView x:Name="listPostions" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="#eee"
Orientation="Vertical">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Latitude}"
TextColor="#f35e20" />
<Label Text="{Binding Longitude}"
HorizontalOptions="EndAndExpand"
TextColor="#503026" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The problem is its not auto updating my app i have seti lockito to be the choosen app in developer options I have location on and can see the movement in Lockito fine but i cant see the orther cordinates from Lockito comming into my app.
This is my andriod function
public class GetMyLocation : Java.Lang.Object, ILocation, ILocationListener
{
public event EventHandler<ILocationEventArgs> locationObtained;
public void ObtainMyLocation()
{
LocationManager lm = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);
lm.RequestLocationUpdates(LocationManager.NetworkProvider,0, 0, this);
}
public void OnLocationChanged(Location location)
{
if (location != null)
{
LocationEventArgs args = new LocationEventArgs();
args.lat = location.Latitude;
args.lng = location.Longitude;
locationObtained(this, args);
}
}
public void OnProviderDisabled(string provider)
{
}
public void OnProviderEnabled(string provider)
{
}
public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
{
}
}
I am doing a project wherein I can change the filter of the image. I am using skiasharp to change the filter of the image. It is like that of CamScanner Application. But when I change the filter to grayscale first and then Lighten and then Sepia and then again back to grayscale I hit save I get Sepia's Image. I understand that the last data being generated is that of sepia's hence it is saving that data. But if I want to change more than 3 times it is not working. Please help me out. Here is my coding.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
BackgroundColor="Black"
x:Class="JC.EditPage">
<ContentPage.Content>
<StackLayout Padding="10,10,10,10" Orientation="Vertical">
<Image x:Name="imageView" HeightRequest="450"
HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand" IsVisible="True"/>
<StackLayout x:Name="canvasStackView" IsVisible="False">
<skia:SKCanvasView HeightRequest="450" PaintSurface="OnCanvasViewPaintSurface" VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand"/>
</StackLayout>
<StackLayout x:Name="canvasLightenStackView" IsVisible="False">
<skia:SKCanvasView HeightRequest="450" PaintSurface="OnCanvasViewPaintSurfaceLighten" VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand"/>
</StackLayout>
<StackLayout x:Name="canvasSepiaStackView" IsVisible="False">
<skia:SKCanvasView HeightRequest="450" PaintSurface="OnCanvasViewPaintSurfaceSepia" VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand"/>
</StackLayout>
<ScrollView Orientation="Horizontal" HorizontalScrollBarVisibility="Never">
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand" x:Name="filterStack" IsVisible="True">
<StackLayout WidthRequest="100" HeightRequest="70" BackgroundColor="White">
<Label Text="Original" FontFamily="Bold" Font="14" TextColor="Black" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="Original_Tapped">
</TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
<StackLayout WidthRequest="100" HeightRequest="70" BackgroundColor="White" >
<Label Text="Grayscale" FontFamily="Bold" Font="14" TextColor="Black" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="Grayscale_Tapped">
</TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
<StackLayout WidthRequest="100" HeightRequest="70" BackgroundColor="White">
<Label Text="Lighten" FontFamily="Bold" Font="14" TextColor="Black" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="Lighten_Tapped">
</TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
<StackLayout WidthRequest="100" HeightRequest="70" BackgroundColor="White" >
<Label Text="Sepia" FontFamily="Bold" Font="14" TextColor="Black" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="Speia_Tapped">
</TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
</StackLayout>
</ScrollView>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand" BackgroundColor="White">
<Image Source="goback.png" HorizontalOptions="StartAndExpand">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="goback_Tapped"/>
</Image.GestureRecognizers>
</Image>
<Image Source="tick.png" HorizontalOptions="EndAndExpand">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="Save_Tapped"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
and here is my XAML.CS file for that -
private async void Grayscale_Tapped(object sender, EventArgs e)
{
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
adjust = false;
canvasEditStackView.IsVisible = false;
canvasSepiaStackView.IsVisible = false;
canvasLightenStackView.IsVisible = false;
imageView.IsVisible = false;
canvasStackView.IsVisible = true;
filterStack.IsVisible = true;
original = false;
byte[] tempArray = await StorageHelper.LoadImage(image, path);
canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurface;
using (Stream stream = new MemoryStream(tempArray))
{
if (stream != null)
{
libraryBitmap = SKBitmap.Decode(stream);
canvasView.InvalidateSurface();
}
}
DependencyService.Get<IProgressInterface>().DismissLoader();
}
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
Console.WriteLine("Hits");
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
using (SKPaint paint = new SKPaint())
{
paint.ColorFilter =
SKColorFilter.CreateColorMatrix(new float[]
{
0.21f, 0.72f, 0.07f, 0, 0,
0.21f, 0.72f, 0.07f, 0, 0,
0.21f, 0.72f, 0.07f, 0, 0,
0, 0, 0, 1, 0
});
canvas.DrawBitmap(libraryBitmap, info.Rect, BitmapStretch.Uniform, paint: paint);
DependencyService.Get<IProgressInterface>().DismissLoader();
}
var snap = surface.Snapshot();
SKData data = snap.Encode();
saveData = data;
}
private async void Lighten_Tapped(object sender, EventArgs e)
{
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
adjust = false;
imageView.IsVisible = false;
canvasEditStackView.IsVisible = false;
canvasStackView.IsVisible = false;
canvasSepiaStackView.IsVisible = false;
canvasLightenStackView.IsVisible = true;
filterStack.IsVisible = true;
original = false;
byte[] tempArray = await StorageHelper.LoadImage(image, path);
canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurfaceLighten;
using (Stream stream = new MemoryStream(tempArray))
{
if (stream != null)
{
libraryBitmap = SKBitmap.Decode(stream);
canvasView.InvalidateSurface();
}
}
DependencyService.Get<IProgressInterface>().DismissLoader();
}
void OnCanvasViewPaintSurfaceLighten(object sender, SKPaintSurfaceEventArgs args)
{
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
using (SKPaint paint = new SKPaint())
{
paint.ColorFilter =
SKColorFilter.CreateColorMatrix(new float[]
{
0.75f, 0.25f, 0.25f, 0, 0,
0.25f, 0.75f, 0.25f, 0, 0,
0.25f, 0.25f, 0.75f, 0, 0,
0, 0, 0, 1, 0
});
canvas.DrawBitmap(libraryBitmap, info.Rect, BitmapStretch.Uniform, paint: paint);
DependencyService.Get<IProgressInterface>().DismissLoader();
}
var snap = surface.Snapshot();
SKData data = snap.Encode();
saveData = data;
}
public async void Speia_Tapped(object sender, EventArgs e)
{
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
adjust = false;
imageView.IsVisible = false;
canvasEditStackView.IsVisible = false;
canvasStackView.IsVisible = false;
canvasLightenStackView.IsVisible = false;
canvasSepiaStackView.IsVisible = true;
filterStack.IsVisible = true;
original = false;
byte[] tempArray = await StorageHelper.LoadImage(image, path);
canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurfaceSepia;
using (Stream stream = new MemoryStream(tempArray))
{
if (stream != null)
{
libraryBitmap = SKBitmap.Decode(stream);
canvasView.InvalidateSurface();
}
}
DependencyService.Get<IProgressInterface>().DismissLoader();
}
void OnCanvasViewPaintSurfaceSepia(object sender, SKPaintSurfaceEventArgs args)
{
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
using (SKPaint paint = new SKPaint())
{
paint.ColorFilter =
SKColorFilter.CreateColorMatrix(new float[]
{
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 0.8f, 0, 0,
0, 0, 0, 1, 0
});
canvas.DrawBitmap(libraryBitmap, info.Rect, BitmapStretch.Uniform, paint: paint);
DependencyService.Get<IProgressInterface>().DismissLoader();
}
var snap = surface.Snapshot();
SKData data = snap.Encode();
saveData = data;
}
and this is my save command.
if (original == true)
{
var editPref = DependencyService.Get<IUserPreferences>();
editPref.SaveString("edit", "false");
await Navigation.PushModalAsync(new desiredLocationStoragePage(path));
}
else
{
var editPref = DependencyService.Get<IUserPreferences>();
editPref.SaveString("edit", "true");
string saveName = fileName;
using (var stream = File.OpenWrite(saveName))
{
saveData.SaveTo(stream);
}
await Navigation.PushModalAsync(new desiredLocationStoragePage(fileName));
}
please help me out guys I am quite stuck after this phase
I hope I got it right, you are using several SKCanvasViews and depending on what "mode" the user chooses in your app, you activate the corresponding surface?
I wouldn't recommend that. Even though it ~kinda~ works, it might become confusing very fast.
My approach to your problem would be to rewrite the view in the following way:
Create an enum containing the names of your filters and another entry for "none", e.g.
public enum Filters
{
None = 0,
Grayscale = 1,
Lighten = 2,
Sepia = 4
}
Then create a property of the type of this enum in your page.
Filters currentFilter = Filters.None;
Now instead of copying your render code 4 times, you could change the main PaintSurface method to something like:
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
Console.WriteLine("Hits");
DependencyService.Get<IProgressInterface>().ShowLoader("Please wait...");
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
using (SKPaint paint = new SKPaint())
{
// check if currentFilter is set to Filters.None
if( (currentFilter & Filters.None) == Filters.None )
{
paint.ColorFilter =
SKColorFilter.CreateColorMatrix(new float[]
{
0.21f, 0.72f, 0.07f, 0, 0,
0.21f, 0.72f, 0.07f, 0, 0,
0.21f, 0.72f, 0.07f, 0, 0,
0, 0, 0, 1, 0
});
}
// check if currentFilter is set to Filters.Lighten
else if ( (currentFilter & Filters.Lighten) == Filters.Lighten)
{
paint.ColorFilter =
SKColorFilter.CreateColorMatrix(new float[]
{
0.75f, 0.25f, 0.25f, 0, 0,
0.25f, 0.75f, 0.25f, 0, 0,
0.25f, 0.25f, 0.75f, 0, 0,
0, 0, 0, 1, 0
});
}
/*
... proceed with other filters accordingly ....
*/
canvas.DrawBitmap(libraryBitmap, info.Rect, BitmapStretch.Uniform, paint: paint);
DependencyService.Get<IProgressInterface>().DismissLoader();
}
var snap = surface.Snapshot();
SKData data = snap.Encode();
saveData = data;
}
So when tapping your SetFilterButton all you need to do is setting the customFilter Property of your page to the corresponding filter and calling
canvasView.InvalidateSurface();
so the surface will be redrawn and then saving the image.
I have a list box defined as below in my xaml. Every item consists of a canvas with an image element inside it. I have declared ManipulationEvents for the image.
<ListBox x:Name="CategoryLB" SelectionChanged="CategoryClicked" Margin="0,131,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Width='460' Height="130" Background="#FF0D6B97" Margin="10,10,10,10" >
<Image Width='480' Height="150" Source="{Binding Page}" Stretch="None" Opacity="1" CacheMode="BitmapCache"
ManipulationDelta="ImageManipulationDelta"
ManipulationCompleted="ImageManipulationCompleted"
ManipulationStarted="ImageManipulationStarted"/>
</Canvas>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The problem is ManipulationDelta is not fired at all. Only ManipulationStarted and ManipulationCompleted gets called and hence my animation does not get the translation values. Looks straightforward to me.
These are the ManipulationEvents
private void ImageManipulationStarted(object sender, ManipulationStartedEventArgs e)
{
FrameworkElement transformElement = ((FrameworkElement)sender) as FrameworkElement;
transformElement.SetHorizontalOffset(0);
}
private void ImageManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
FrameworkElement transformElement = ((FrameworkElement)sender) as FrameworkElement;
if (Math.Abs(e.TotalManipulation.Translation.X) > transformElement.ActualWidth / 3)
{
if (e.TotalManipulation.Translation.X < 0.0)
{
ToDoItemDeletedAction(transformElement);
}
else
{
ToDoItemCompletedAction(transformElement);
}
}
else
{
ToDoItemBounceBack(transformElement);
}
}
private void ImageManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
FrameworkElement transformElement = ((FrameworkElement)sender) as FrameworkElement;
// handle the drag to offset the element
double offset = transformElement.GetHorizontalOffset().Value + e.DeltaManipulation.Translation.X;
transformElement.SetHorizontalOffset(offset);
}
Anything that Im missing here?
your code is all right but the problem is that the delta event will not fire on the emulator and i have tested your code both on emulator and device and its working fine on device so dont worry and test your code on device ....
i have done manipulation on image which goes something like this ..
I hope this might help you ..
<Image x:Name="imgViewer" CacheMode="BitmapCache" Source="/MetroImages/mapmetro.png" Stretch="Uniform">
<Image.RenderTransform>
<ScaleTransform x:Name="scaleTrans" ScaleX="2" ScaleY="2" CenterX="150" CenterY="200" />
</Image.RenderTransform>
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener
PinchStarted="GestureListener_PinchStart"
PinchDelta="GestureListener_PinchDelta"
PinchCompleted="GestureListener_PinchComplete"
DragStarted="GestureListener_DragStart"
DragDelta="GestureListener_DragDelta"
DragCompleted="GestureListener_DragCompleted"/>
</toolkit:GestureService.GestureListener>
</Image>
and then in eventhandlers
private readonly DispatcherTimer m_animationTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(10) };
private double _cx, _cy;
private void GestureListener_PinchStart(object sender, PinchStartedGestureEventArgs e)
{
Point p1 = e.GetPosition(imgViewer, 0);
Point p2 = e.GetPosition(imgViewer, 1);
scaleTrans.CenterX = (p1.X + ((p2.X - p1.X) / 2));
scaleTrans.CenterY = (p1.Y + ((p2.Y - p1.Y) / 2));
_cx = scaleTrans.ScaleX;
_cy = scaleTrans.ScaleY;
}
private void GestureListener_PinchDelta(object sender, PinchGestureEventArgs e)
{
// Compute new scaling factors
double cx = _cx * e.DistanceRatio;
double cy = _cy * e.DistanceRatio;
// If they're between 1.0 and 4.0, inclusive, apply them
if (cx >= 1.0 && cx <= 4.0 && cy >= 1.0 && cy <= 4.0)
{
if ((cy - 1) < 0.1 && (cx - 1) < 0.1)
cx = cy = 1;
scaleTrans.ScaleX = cx;
scaleTrans.ScaleY = cy;
}
}
private void GestureListener_PinchComplete(object sender, PinchGestureEventArgs e)
{
}
private void GestureListener_DragStart(object sender, DragStartedGestureEventArgs e)
{
}
private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
{
scaleTrans.CenterX = (scaleTrans.CenterX - e.HorizontalChange);
scaleTrans.CenterY = (scaleTrans.CenterY - e.VerticalChange);
if (scaleTrans.CenterX < 0)
{
scaleTrans.CenterX = 0;
}
else if (scaleTrans.CenterX > imgViewer.ActualWidth)
scaleTrans.CenterX = imgViewer.ActualWidth;
if (scaleTrans.CenterY < 0)
{
scaleTrans.CenterY = 0;
}
else if (scaleTrans.CenterY > imgViewer.ActualHeight)
scaleTrans.CenterY = imgViewer.ActualHeight;
}
private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
{
}
I filled the icBoard with 50 Cell objects, so each Rectangle object has Cell as data object. Now, I want according to index or cell object to get the corresponding Rectangle element. For example I want to get the Rectangle in index=15. Not it's data but the Rectangle itself.
How I can do this?
public MainPage()
{
InitializeComponent();
var cells = new List<Cell>();
for (int i = 0; i < 50; i++)
{
cells.Add(new Cell());
}
icCells.ItemsSource = cells;
}
public void sector_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
//some code
//....
var tappedRectangle = (sender as Rectangle);
var spesificRectangle = SOMEHOW_GET_RECTANGLE_AT_POSITION_15;
}
<ItemsControl Name="icBoard" Grid.Column="0" Margin="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Fill="#501e4696" Width="30" Height="30" Margin="1" Tap="sector_Tap" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
I believe this might work:
ContentPresenter contentPresenter = itemsControl.ItemContainerGenerator.ContainerFromIndex(15) as ContentPresenter;
Rectangle rectangle= FindVisualChild<Rectangle>(contentPresenter );
if (rectangle != null)
{
}
public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}