How to retrieve an element from ItemsControl c# and Xaml? - c#

I am creating a simple game for windows store using c# and xaml.
I want to change the colour of a rectangle when clicked.
I tried different method of conversion from sender object but I was unable to fix the bug. Please help me out. I have "onTapped" event for ItemsControl.
Xaml File :
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ItemsControl Grid.Row="1" x:Name="rectangleItems" Tapped="RectTapped">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid x:Name="myWrapGrid" Height="400"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- The sequence children appear depends on their order in
the panel's children, not necessarily on where they render
on the screen. Be sure to arrange your child elements in
the order you want them to transition into view. -->
<ItemsControl.Items >
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10" />
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
<Rectangle Fill="Red" Width="100" Height="100" Margin="10"/>
</ItemsControl.Items>
</ItemsControl>
</Grid>
This is the code for ItemsControl event.
private void RectTapped(object sender, TappedRoutedEventArgs e)
{
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 0, 255, 0);
Rectangle uiElement = (Rectangle)rectangleItems.ContainerFromIndex(1);
Rectangle rc = (Rectangle)uiElement;
rc.Fill = mySolidColorBrush;
}
In this case I have manually specified the element of index 1 but I would like to change the colour of the rectangle that was clicked.
Thanks.

You should bind event to Rectangles, not the ItemControl, and then use sender object of the event as Rectangle to change it's properties:
private void RectEvent(object sender,EventArgs args)
{
var rectangle = sender as Rectangle;
//rest of your code
}
In order to bind event to your rectangles you can iterate thought the "rectangleItems" collection that you have in your code.
If binding such event is not an option, then you can use GetPosition method from TappedRoutedEventArgs (see documentation here) and then search for your rectangle by this value.

Related

Problem with loading picture from website to WPF Image using URL

I've made a snake game. As in the title - I've tried to load a picture from website to the source of WPF Image using URL. My goal was to load a random picture from website as a bitmap every time the snake collects the food on the map, but the most important thing was that it shouldn't be loaded when the program executes, but after the snake collects the food. So I've created a string array, where I placed 5 url links to the pictures from the website and then I wanted to use Random() to choose a random link to the picture and place it to the source of WPF Image. But when the snake collects the food, nothing happens. And my question is: is my code wrong? Here's my code:
XAML CODE
<Window x:Class="Snake_Game.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Snake_Game"
mc:Ignorable="d"
Title="Snake The Game"
SizeToContent="WidthAndHeight"
ContentRendered="Window_ContentRendered"
KeyUp="Window_KeyUp">
<Border BorderBrush="Black" BorderThickness="8">
<Canvas Name="GameBoard"
ClipToBounds="True"
Background="Black"
Height="1000"
Width="1000">
<Rectangle x:Name="ScoreBoard"
Fill="#FF7B2D96"
Height="1000"
Canvas.Left="706"
Stroke="Black"
Width="294"/>
<Label x:Name="PointsPanel"
Content="POINTS"
Canvas.Left="804"
Canvas.Top="27"
Height="29"
Width="95"
FontWeight="Bold"
FontSize="14"
Background="#FFE72626"/>
<Image x:Name="ImagePanel"
Height="355"
Canvas.Left="724"
Canvas.Top="272"
Width="266"
Stretch="UniformToFill"
RenderOptions.BitmapScalingMode="Fant"
StretchDirection="DownOnly"
MaxHeight="355"
MaxWidth="266">
<Image.OpacityMask>
<ImageBrush/>
</Image.OpacityMask>
</Image>
<Label x:Name="Score"
Content=""
Canvas.Left="804"
Canvas.Top="61"
Height="50"
Width="95"
FontWeight="Bold"
FontSize="36"
FontFamily="SimSun"/>
</Canvas>
</Border>
</Window>
Method used to load a random picture (from string array):
private void GetRandomImage()
{
string[] images =
{
"http://cdn.pixabay.com/photo/2015/02/28/15/25/snake-653639_1280.jpg",
"http://cdn.pixabay.com/photo/2014/12/25/14/54/snake-579682_1280.jpg",
"http://cdn.pixabay.com/photo/2015/02/28/15/25/rattlesnake-653642_1280.jpg",
"http://cdn.pixabay.com/photo/2012/10/10/05/07/grass-snake-60546_1280.jpg",
"http://cdn.pixabay.com/photo/2010/12/14/16/46/snake-3237_1280.jpg"
};
BitmapImage bitmapImage = new BitmapImage(new Uri(images[rnd.Next(images.Length)]));
ImagePanel.Source = bitmapImage;
}
Just remove OpacityMask. You do not set ImageSource of ImageBrush, so there is no reason to have OpacityMask.
<Border BorderBrush="Black" BorderThickness="8">
<Canvas Name="GameBoard" ClipToBounds="True" Background="Black" Height="1000" Width="1000"
>
<Rectangle x:Name="ScoreBoard" Fill="#FF7B2D96" Height="1000" Canvas.Left="706" Stroke="Black" Width="294"/>
<Label x:Name="PointsPanel" Content=" POINTS" Canvas.Left="804" Canvas.Top="27" Height="29" Width="95" FontWeight="Bold" FontSize="14" Background="#FFE72626"/>
<Image x:Name="ImagePanel" Height="355" Canvas.Left="724" Canvas.Top="272" Width="266" Stretch="UniformToFill" RenderOptions.BitmapScalingMode="Fant" StretchDirection="DownOnly" MaxHeight="355"
MaxWidth="266">
</Image>
<Label x:Name="Score" Content="" Canvas.Left="804" Canvas.Top="61" Height="50" Width="95" FontWeight="Bold" FontSize="36" FontFamily="SimSun"/>
</Canvas>
</Border>

how to add UI elements programmatically in canvas in silverlight?

I have a canvas inside grid. I want to add the controls dynamically(text-block and image). I am using the following code but it is not showing up anything.
XAML:
<Grid x:Name="BaseGrid"
Background="White"
Grid.Row="2">
<Canvas x:Name="RootCanvas"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Visibility="Collapsed"
Canvas.ZIndex="0">
<Canvas x:Name="BaseCanvas"
CacheMode="BitmapCache"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Canvas.Left="0"
Canvas.Top="0"
Canvas.ZIndex="0">
<Canvas.Clip>
<RectangleGeometry x:Name="BaseCanvasClip"/>
</Canvas.Clip>
<Canvas x:Name="DrawingCanvas"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Canvas.Left="0"
Canvas.Top="0"
Canvas.ZIndex="10">
</Canvas>
<Canvas x:Name="TransparentCanvas"
Background="Transparent"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Canvas.Left="0"
Canvas.Top="0"
Canvas.ZIndex="100"
Visibility="Collapsed">
</Canvas>
</Canvas>
</Canvas>
</Grid>
</Grid>
Code:
TextBlock txtBlk = new TextBlock();
txtBlk.FontSize = 14;
txtBlk.Foreground = new SolidColorBrush(Colors.Red);
txtBlk.Text = CreateConceptTextBox.Text;
Canvas.SetTop(txtBlk, 100);
Canvas.SetLeft(txtBlk, 450);
//Grid.SetRow(txtBlk, 100);
//Grid.SetColumn(txtBlk, 450);
linkDiscovery.DrawingCanvas.Children.Add(txtBlk);
I am concern with "DrawingCanvas". What is that I am missing here?
You have the Visibility of your RootCanvas set to Collapsed, which effectively hides it and all of its children, including the DrawingCanvas.

WPF Window - Fade Different parts of the same window

I have a basic WPF windows with the markup as specific below:
<Window x:Class="Application.SomeWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SomeWindow"
Topmost="True" WindowStyle="None" Height="39" Width="400"
ResizeMode="NoResize" ShowInTaskbar="False"
WindowStartupLocation="Manual" Background="Transparent"
Closing="Window_Closing" AllowsTransparency="True" Opacity="0">
<Border Background="CornflowerBlue" BorderBrush="Black" BorderThickness="0,0,0,0" CornerRadius="5,5,5,5" Opacity="0.75">
<Grid>
<!-- Display bar -->
<Image Grid.Row="1" Height="24" Margin="7,7,0,0" Name="img1" Stretch="Fill" VerticalAlignment="Top" Source="/Application;component/Images/dashboard/1.png" HorizontalAlignment="Left" Width="13" />
<Image Height="24" Margin="19,7,47,0" Name="image21" Source="/Application;component/Images/dashboard/2.png" Stretch="Fill" VerticalAlignment="Top" Grid.Row="1" Grid.ColumnSpan="2" />
<!-- Button 1 -->
<Button Style="{DynamicResource NoChromeButton}" Height="27" Margin="0,5,25,0" Name="btn1" Click="btn1_Click" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" Width="23" ToolTip="1">
<Image Height="26" HorizontalAlignment="Right" Name="img1" Source="/Application;component/Images/dashboard/3.png" VerticalAlignment="Top" Width="22" Stretch="Fill" />
</Button>
<!-- Button 2 -->
<Button Style="{DynamicResource NoChromeButton}" Height="27" Margin="0,5,5,0" Name="btn2" Click="btn2_Click" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" Width="23" ToolTip="2">
<Image Height="26" HorizontalAlignment="Right" Name="img2" Source="/Application;component/Images/dashboard/4.png" VerticalAlignment="Top" Width="22" Stretch="Fill" />
</Button>
</Grid>
</Border>
</Window>
Here is what it looks like now:
What I'd really like to do is make it so that initially looks like this:
Then, once mouseover happens, to fade background opacity in from 0 so it looks like the first image. The problem is that if I set the Border or Grid Background color to Transparent with the goal of fading in on mouseover, then everything inside the Border or Grid is affected as well.
Is there a way to manage the opacities of window and its UI elements seperately? Or perhaps there is a totally different route to take to get this background fade on mouseover? Thanks.
There are two options. Number one is to just move the outer border inside the grid, as the first child (and have the other controls alongside it, not in it). That way it will fade by itself, but still be behind the other controls. You will of course either have to set ColumnSpan/RowSpan, or wrap the entire thing in another Grid.
The second option is to just fade the background, not the entire border:
<Border ...>
<Border.Background>
<SolidColorBrush Color="CornflowerBlue" Opacity="0.5"/>
</Border.Background>
...
try this trick - draw a rectangle or border with dimensions bind to parent or ElementName.
It won't affect rest of elements of tree. Works for me.
<Grid x:Name="abc">
<Border
Width="{Binding ActualWidth, ElementName=abc}"
Height="{Binding ActualHeight, ElementName=abc}"
Background="Blue"
Opacity="0.5"/>
//buttons or inner grid
...
</Grid>
If you don'w want to use ElementName, simply replace Width and Height by
Width="{Binding ActualWidth, Source={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
Height="{Binding ActualHeight, Source={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"

Automatic scroll view in windows phone 8

I have an image scroll view, I import image from remote server but I want to scroll the image automatically, help me how to scroll the image automatically
my xaml code for image scroll view
<ScrollViewer x:Name="ImgScrollViewer"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" >
<StackPanel Orientation="Horizontal" x:Name="ImagesSP"
ScrollViewer.ManipulationMode="Control"
ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Height="124" Width="3690"
Loaded="ImagesSP_Loaded_1" >
<!--<StackPanel.RenderTransform>
<TranslateTransform Y="550"/>
</StackPanel.RenderTransform-->
<Image Source="http://technomindtech.com/1tele-pixel.com/ad/logo_banner.jpg" Width="500" Height="45" Stretch="Fill" VerticalAlignment="Top" />
<Image Source="http://technomindtech.com/1tele-pixel.com/ad/images.jpeg" Width="500" Height="45" Stretch="Fill" VerticalAlignment="Top" />
<Image Source="http://technomindtech.com/1tele-pixel.com/ad/banner.jpg" Width="500" Height="45" Stretch="Fill" VerticalAlignment="Top" />
<Image Source="http://technomindtech.com/1tele-pixel.com/ad/images.jpeg" Width="500" Height="45" Stretch="Fill" VerticalAlignment="Top" />
<Image Source="Images\MediumGray.png" Width="480" Height="400" Stretch="Fill" />
</StackPanel>
</ScrollViewer>
My cs code
namespace BogheApp
{
public partial class MainPage : BasePage
{
public MainPage()
{
InitializeComponent();
}
private void ImagesSP_Loaded_1(object sender, RoutedEventArgs e)
{
}
}
}
You need to calculate the offset where you want to scroll to, and then use ScrollToVerticalOffset(your_offset_value) method. Now how you calculate the offset depends on what exactly you want to achieve, so more details is needed to answer this.

Images in List in Panorama throwing Out of memory Exception

I have a Panorama page where list of feeds are coming from previous page which have some images. So if the size of that list increases it throws out of memory exception. Also my Pivot is in template, so I am not even able to do dispose action for images. Please help. Stuck in the issue for a long.
Constants.messageDiscArray, I am setting in previous page to a Constants file. And aslo the Panorama is in a template so I am also not able to perform any function on the images for the garbage collection.
Any help would be appreciated thanks.
This is my xaml code :
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,0,0">
<controls:Panorama x:Name="FeedsPanorama" Title="Dashboard Column" ItemsSource="{Binding Constants.messageDiscArray}" >
<controls:Panorama.ItemTemplate>
<DataTemplate>
<Grid Margin="0,-300,0,0">
<Grid Margin="0,0,0,0">
<Image Height="30" HorizontalAlignment="Left" Margin="15,319,0,0" Name="image11" Stretch="Fill" VerticalAlignment="Top" Width="30" Source="/WpControlsExample;component/Images/assigns.png" />
<Image Height="30" HorizontalAlignment="Left" Margin="340,319,0,0" Name="image13" Stretch="Fill" VerticalAlignment="Top" Width="30" Source="{Binding spamURL}" />
<Image Height="30" HorizontalAlignment="Left" Margin="376,319,0,0" Name="image14" Stretch="Fill" VerticalAlignment="Top" Width="30" Source="{Binding sentimentURL}" />
</Grid>
</Grid>
</DataTemplate>
</controls:Panorama.ItemTemplate>
</controls:Panorama>
</Grid>
</Grid>
And below is my C# code
public partial class MessageDescription : PhoneApplicationPage
{
private ObservableCollection<InboxItem> msArray = new ObservableCollection<InboxItem>();
public MessageDescription()
{
InitializeComponent();
loadPanoramaFeeds();
}
private void loadPanoramaFeeds()
{
for(int i=0;i< Constants.messageDiscArray.Count;i++){
msArray.Add(Constants.messageDiscArray[i]);
}
this.FeedsPanorama.ItemsSource = msArray;
this.FeedsPanorama.DefaultItem = this.FeedsPanorama.Items[Constants.messageIndex];
}
}

Categories