how to make auto flip view XAML - c#

I have creaed flipview in XAML page i want to make that slides transtaction automatically how can i do that?
<StackPanel x:Name="StackPanel_1" Margin="541,42,71,160" Orientation="Vertical" Grid.Row="1">
<FlipView x:Name="flipView1" Width="480" Height="270"
BorderBrush="Black" BorderThickness="1">
<Grid Margin="0,0,-8,-8">
<Image Source="Assets/Logo.png" Width="480" Height="270" Stretch="UniformToFill"/>
<Border Background="#A5000000" Height="80" VerticalAlignment="Bottom">
<TextBlock Text="Logo" FontFamily="Segoe UI" FontSize="26.667" Foreground="#CCFFFFFF" Padding="15,20" Margin="0,0,8,8"/>
</Border>
</Grid>
<Grid Margin="0,0,-8,-8">
<Image Source="Assets/SplashScreen.png" Width="480" Height="270" Stretch="UniformToFill" />
<Border Background="#A5000000" Height="80" VerticalAlignment="Bottom">
<TextBlock Text="Logo11111111" FontFamily="Segoe UI" FontSize="26.667" Foreground="#CCFFFFFF" Padding="15,20" Margin="0,0,8,8"/>
</Border>
</Grid>
<Grid Height="270" Width="480">
<Image Source="Assets/SmallLogo.png" Width="480" Height="270" Stretch="UniformToFill" />
<Border Background="#A5000000" Height="80" VerticalAlignment="Bottom">
<TextBlock Text="Logo222222222" FontFamily="Segoe UI" FontSize="26.667" Foreground="#CCFFFFFF" Padding="15,20" Margin="0,0,8,8"/>
</Border>
</Grid>
</FlipView>

You'll need to update the flipview's SelectedIndex property.
The most straightforward would be to run a DispatcherTimer and increment SelectedIndex every however long you'd like. When it gets to the end then set it back to 0. The hitch is that the FlipView will animate when you switch the index by one, but not when you jump pages. If you want to loop back from the last page to the first it will jump rather than animate. You might want to reverse direction instead of going direct to 0.
int change = 1;
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(2);
timer.Tick += (o, a) =>
{
// If we'd go out of bounds then reverse
int newIndex = flipView1.SelectedIndex + change;
if (newIndex >= flipView1.Items.Count || newIndex < 0)
{
change *= -1;
}
flipView1.SelectedIndex += change;
};
timer.Start();
If you want to set this up completely in XAML without code then you can create a Storyboarded animation in Xaml to animate the SelectedIndex and trigger it with an EventTriggerBehavior behavior when page loads.
<Page.Resources>
<Storyboard x:Name="AutoFlipView" RepeatBehavior="Forever" AutoReverse="True">
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Selector.SelectedIndex)" Storyboard.TargetName="flipView1">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<x:Int32>0</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:1">
<DiscreteObjectKeyFrame.Value>
<x:Int32>1</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:2">
<DiscreteObjectKeyFrame.Value>
<x:Int32>2</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:3">
<DiscreteObjectKeyFrame.Value>
<x:Int32>2</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</Page.Resources>
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Loaded">
<Media:ControlStoryboardAction Storyboard="{StaticResource AutoFlipView}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>

I wrote a hacky prototype that shows how you can animate the entire cycle by rearranging the elements in the FlipView...
C#
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App4
{
public class CyclingFlipView : FlipView
{
public async Task Cycle()
{
if (this.ItemsSource != null)
{
var list = (IList)this.ItemsSource;
if (list.Count == 0)
{
return;
}
SelectionChangedEventHandler handler = null;
var tcs = new TaskCompletionSource<bool>();
handler = (s, e) =>
{
tcs.SetResult(true);
this.SelectionChanged -= handler;
};
this.SelectionChanged += handler;
this.SelectedIndex = (this.SelectedIndex + 1) % list.Count;
await tcs.Task;
await Task.Delay(500);
var i = this.SelectedIndex;
this.SelectedItem = null;
var item = list[0];
list.RemoveAt(0);
list.Add(item);
this.SelectedIndex = i - 1;
}
else if (this.Items != null)
{
if (this.Items.Count == 0)
{
return;
}
SelectionChangedEventHandler handler = null;
var tcs = new TaskCompletionSource<bool>();
handler = (s, e) =>
{
tcs.SetResult(true);
this.SelectionChanged -= handler;
};
this.SelectionChanged += handler;
this.SelectedIndex = (this.SelectedIndex + 1) % this.Items.Count;
await tcs.Task;
await Task.Delay(500);
var i = this.SelectedIndex;
this.SelectedItem = null;
var item = this.Items[0];
this.Items.RemoveAt(0);
this.Items.Add(item);
this.SelectedIndex = i - 1;
}
}
public async Task AutoCycle()
{
while (true)
{
this.Cycle();
await Task.Delay(1000);
}
}
}
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var fv = new CyclingFlipView();
fv.ItemsSource = new ObservableCollection<int>(Enumerable.Range(0, 4));
fv.ItemTemplate = (DataTemplate)this.Resources["ItemTemplate"];
this.Content = fv;
fv.AutoCycle();
}
}
}
XAML
<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate
x:Key="ItemTemplate">
<Border
Background="GreenYellow">
<TextBlock
Text="{Binding}"
FontSize="144"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
</DataTemplate>
</Page.Resources>
<Grid
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>

Related

Constructing wpf in-code for Transform Group based on the xaml code

I am having problem in constructing the in-code program based on the given xaml code. Especially for the Transform Group part and the Trigger part.
<Window x:Class="newStackOverflow.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:newStackOverflow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Storyboard x:Key="Storyboard1">
<DoubleAnimationUsingKeyFrames
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
Storyboard.TargetName="rectangle">
<EasingDoubleKeyFrame KeyTime="0:0:10" Value="300"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Canvas x:Name="canvas" VerticalAlignment="Stretch" Background="Green">
<Rectangle x:Name="rectangle"
Fill="#FFF4F4F5" Stroke="Black"
Height="100" Width="100"
Canvas.Left="10" Canvas.Top="10"
RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1"/>
<TranslateTransform X="50" Y="20"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
</Canvas>
<Button Content="Button"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Padding="10 5" Margin="10" Grid.Row="1">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
Can you give any ideas in developing the in-code part?Thanks in advance!:D
these are my codes. When i tried the codes, it say that the s.Begin(rectangle) exception user unhandled.
public partial class MainWindow : Window
{
private Storyboard s;
public MainWindow()
{
InitializeComponent();
Button button = new Button();
button.Height = 28;
button.Width = 58;
button.HorizontalAlignment = HorizontalAlignment.Center;
button.VerticalAlignment = VerticalAlignment.Center;
button.Content = "Button";
button.Name = "button";
this.RegisterName(button.Name, button);
Rectangle rectangle = new Rectangle();
rectangle.Width = 100;
rectangle.Height = 100;
rectangle.Fill = new SolidColorBrush(Colors.White);
rectangle.Stroke = new SolidColorBrush(Colors.Black);
Canvas.SetLeft(rectangle, 10);
Canvas.SetTop(rectangle,10);
canvas1.Children.Add(rectangle);
rectangle.Name = "rectangle";
TranslateTransform tt = new TranslateTransform();
ScaleTransform st = new ScaleTransform();
TransformGroup tg = new TransformGroup();
tg.Children.Add(tt);
tg.Children.Add(st);
button.RenderTransform = tg;
Duration duration = new Duration(TimeSpan.FromMilliseconds(10));
DoubleAnimationUsingKeyFrames myDoubleAnim = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame myDoubleKey = new EasingDoubleKeyFrame();
Storyboard s = new Storyboard();
Storyboard.SetTargetName(myDoubleAnim, button.Name);
Storyboard.SetTargetProperty(myDoubleAnim, new PropertyPath("RenderTransform.Children[3].Y"));
myDoubleKey.KeyTime = KeyTime.FromPercent(1);
myDoubleKey.Value = 300;
myDoubleAnim.KeyFrames.Add(myDoubleKey);
s.Children.Add(myDoubleAnim);
s.Begin(rectangle);
//button.Loaded += new RoutedEventHandler(buttonLoaded);
}

EllipseGeometry Shrink & Fade Without Exceeding Canvas Bounds in C# WPF

How to make animation stay within the canvas at bigger sizes when the user clicks around the edge of the canvas? Currently, if sizes are too big and if user clicks near the edge of the canvas, the ellipse will grow outside of the canvas to cover the buttons. I need the animation to stay within the canvas to make it look like a slice of pizza essentially.
Should look like this:
Size 50 where user clicks near top left of canvas
Currently looks like this:
Size 50 where user clicks near top left of canvas
Xaml:
<Window.Resources>
<Storyboard x:Key="anim">
<DoubleAnimation
Storyboard.TargetName="myCircle"
Storyboard.TargetProperty="RadiusX"
AutoReverse="True"/>
<DoubleAnimation
Storyboard.TargetName="myCircle"
Storyboard.TargetProperty="RadiusY"
AutoReverse="True"/>
<DoubleAnimation
Storyboard.TargetName="path"
Storyboard.TargetProperty="Opacity"
AutoReverse="True"/>
</Storyboard>
</Window.Resources>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="23"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" Margin="0,0,0,1">
<Menu DockPanel.Dock="Top" Height="23">
<MenuItem Header="Main" RenderTransformOrigin="-1.896,0.643" HorizontalAlignment="Left" Width="39" Height="23">
<MenuItem Header="Exit, Esc" Click="MenuItem_Click_Exit"/>
</MenuItem>
</Menu>
</DockPanel>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Name="pane">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Name="pane2">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Content="Size" Grid.Row="0" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Fill Color" Grid.Row="1" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Stroke Thickness" Grid.Row="2" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Stroke Color" Grid.Row="3" Grid.Column="0" VerticalAlignment="Top" Height="25"/>
<Slider x:Name="Slider_Size" Grid.Row="0" Grid.Column="1" Height="20" Width="45"
Minimum="5" Maximum="50"
AutoToolTipPlacement="BottomRight"
TickFrequency="1"
IsSnapToTickEnabled="True"
PreviewMouseUp="Slider_Size_PreviewMouseUp"/>
<Label Name="tempSize" Content="{Binding Path=Value, ElementName=Slider_Size}" Margin="0,25,0,131" Grid.Row="3" Visibility="Hidden"/>
<ComboBox Name="ComboBox_FillColor" Grid.Row="1" Grid.Column="1" Height="20" Width="45" SelectionChanged="ComboBox_FillColor_Selected"/>
<TextBox Name="textBox" Grid.Row="2" Grid.Column="1" Height="20" Width="45" TextChanged="textBox_TextChanged"/>
<ComboBox Name="ComboBox_StrokeColor" Grid.Row="3" Grid.Column="1" VerticalAlignment="Top" Height="20" Width="45" SelectionChanged="ComboBox_StrokeColor_Selected"/>
</Grid>
<Border Name ="border" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Black" Grid.Column="1" BorderThickness="2">
<Canvas Name="canvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseDown="Canvas_MouseDown">
<Path x:Name="path">
<Path.Data>
<EllipseGeometry x:Name="myCircle"/>
</Path.Data>
</Path>
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background>
</Canvas>
</Border>
</Grid>
</Grid>
C#:
public partial class MainWindow : Window
{
private int size;
private SolidColorBrush fillColor;
private SolidColorBrush strokeColor;
private List<SolidColorBrush> colors;
private int fillIndex;
private int strokeIndex;
private int strokeThickness = 1;
private int fillColorDefault;
private int strokeColorDefault;
private Point? _start = null;
public MainWindow()
{
InitializeComponent();
addColors();
textBox.Text = strokeThickness.ToString();
parse();
}
private void MenuItem_Click_Exit(object sender, RoutedEventArgs e) { Environment.Exit(1); }
private void Window_KeyUp_ESC(object sender, KeyEventArgs e)
{
if (Key.Escape == e.Key)
MenuItem_Click_Exit(sender, e);
}
private void addColors()
{
colors = typeof(Brushes).GetProperties().Select(p => p.GetValue(null, null) as SolidColorBrush).ToList();
int count = 0;
foreach (SolidColorBrush color in colors)
{
ComboBox_FillColor.Items.Add(new Rectangle() { Height = 12, Width = 17.5, Fill = color });
ComboBox_StrokeColor.Items.Add(new Rectangle() { Height = 12, Width = 17.5, Fill = color });
if (color.Color == Colors.Red)
{
fillIndex = count;
fillColor = colors[fillIndex];
ComboBox_FillColor.SelectedIndex = count;
fillColorDefault = count;
}
if (color.Color == Colors.Black)
{
strokeIndex = count;
strokeColor = colors[strokeIndex];
ComboBox_StrokeColor.SelectedIndex = count;
strokeColorDefault = count;
}
count++;
}
}
private void ComboBox_FillColor_Selected(object sender, RoutedEventArgs e) { fillIndex = ComboBox_FillColor.SelectedIndex; fillColor = colors[fillIndex]; }
private void ComboBox_StrokeColor_Selected(object sender, RoutedEventArgs e) { strokeIndex = ComboBox_StrokeColor.SelectedIndex; strokeColor = colors[strokeIndex]; }
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
path.Stroke = strokeColor;
path.StrokeThickness = strokeThickness;
path.Fill = fillColor;
path.HorizontalAlignment = HorizontalAlignment.Stretch;
path.VerticalAlignment = VerticalAlignment.Stretch;
path.Stretch = Stretch.None;
path.SetValue(Grid.ColumnProperty, 1);
_start = Mouse.GetPosition((UIElement)sender);
myCircle.Center = (Point)_start;
var sb = FindResource("anim") as Storyboard;
var x = sb.Children.First() as DoubleAnimation;
x.To = 2 * size;
x.Duration = new Duration(TimeSpan.FromSeconds(0.5));
var y = sb.Children.ElementAt(1) as DoubleAnimation;
y.To = 2 * size;
y.Duration = new Duration(TimeSpan.FromSeconds(0.5));
var z = sb.Children.Last() as DoubleAnimation;
z.From = 0.0;
z.To = 1.0;
z.Duration = new Duration(TimeSpan.FromSeconds(0.5));
sb.Begin(path);
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
//regex where any string of chars besides numbers
Regex pattern = new Regex(#"^([^0-9]*)$", RegexOptions.Compiled);
Match result = pattern.Match(textBox.Text);
if (textBox.Text.ToString() == string.Empty)
return;
else if (result.Success)
{
MessageBox.Show("Invalid character entered. Integer numbers only. Stroke Thickness will be reseted to a default of 1.");
strokeThickness = 1;
textBox.Text = strokeThickness.ToString();
textBox.SelectAll();
}
else
{
int x;
if (int.TryParse(textBox.Text, out x))
strokeThickness = int.Parse(textBox.Text);
}
}
private void Slider_Size_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
parse();
}
private void parse()
{
int x;
if (int.TryParse(tempSize.Content.ToString(), out x))
size = x;
}
}
}
So you don't need the ellipse to stay within the Canvas, but you want to clip away the parts leaving it, right? Just set ClipToBounds (of Canvas) to true (can be done in Xaml).

Showing canvas children in listbox

I'm new here so please excuse my if I missed to add something needed to answer my question.
So heres my question:
I am trying to add shapes to a canvas while also wanting to show a list of them in a listbox, to make them changeable (size,position, etc.). I am using WPF. Is there a way to do so?
And if it doesnt bother you: Is there maybe a question or website or whatever about how to dynamically draw shapes(circle,ellipse,rect, etc.) with mouse events?
I hope you can help me. Thanks in advance.
Edit:
Given the fact that I have:
public partial class MainWindow : Window
{
public ObservableCollection<string> Baselist = new ObservableCollection<string>();
public ObservableCollection<string> Crystallist = new ObservableCollection<string>();
public ObservableCollection<Shape> Shapelist = new ObservableCollection<Shape>();
public MainWindow()
{
this.ResizeMode = System.Windows.ResizeMode.CanMinimize;
InitializeComponent();
InitializeLists(Baseforms,CrystalGroups);
}
private void InitializeLists(ComboBox Baseforms, ComboBox CrystalGroups)
{
Baseforms.ItemsSource = Baselist;
CrystalGroups.ItemsSource = Crystallist;
Shape Circle = new Ellipse();
Circle.Stroke = System.Windows.Media.Brushes.Black;
Circle.Fill = System.Windows.Media.Brushes.DarkBlue;
Circle.HorizontalAlignment = HorizontalAlignment.Left;
Circle.VerticalAlignment = VerticalAlignment.Center;
Circle.Width = 50;
Circle.Height = 50;
Shapelist.Add(Circle);
}
How can I use an ItemsControl to show the shapes in Shapelist in an canvas while also listing them in a Listbox?
Hope this makes the question less broad.
Please try the next solution:
Updated version (xaml and code behind)
DetailsList list view - presents detailed data based on ShapeDataPresentation class (supports multi-select). Shows data by data template named ShapeDataPresentationDataTemplate.
ShapesPresentor items control - presents shapes on canvas (doesn't support multi-select only one can be selected).
ListView XAML code ("This" is the name of the ListView containing window)
<Window x:Class="ListViewWithCanvasPanel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:listViewWithCanvasPanel="clr-namespace:ListViewWithCanvasPanel"
Title="MainWindow" Height="350" Width="525" x:Name="This" ResizeMode="CanResize">
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2.5*"></ColumnDefinition>
<ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ListView x:Name="DetailsList" Panel.ZIndex="999" Grid.Column="0" ItemsSource="{Binding ElementName=This, Path=Shapes}" SelectionMode="Extended" SelectionChanged="Selector_OnSelectionChanged">
<ListView.Resources>
<DataTemplate x:Key="ShapeDataPresentationDataTemplate" DataType="listViewWithCanvasPanel:ShapeDataPresentation">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Name, StringFormat={}{0:N0}%}"></TextBlock>
<TextBlock Grid.Column="1">
<Run Text="W:"></Run>
<Run Text="{Binding OriginalRectAroundShape.Width}"></Run>
</TextBlock>
<TextBlock Grid.Column="2">
<Run Text="H:"></Run>
<Run Text="{Binding OriginalRectAroundShape.Height}"></Run>
</TextBlock>
</Grid>
</DataTemplate>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate DataType="Shape">
<ContentControl Content="{Binding Tag}" ContentTemplate="{StaticResource ShapeDataPresentationDataTemplate}"></ContentControl>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>
<GridSplitter Grid.Column="0" Width="3" Background="Blue" Panel.ZIndex="999"
VerticalAlignment="Stretch" HorizontalAlignment="Right" Margin="0"/>
<ItemsControl Grid.Column="1" x:Name="ShapesPresentor" ItemsSource="{Binding ElementName=This, Path=Shapes}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
MouseDown="UIElement_OnMouseDown">
<!--<ListView.Resources>
<ControlTemplate x:Key="SelectedTemplate" TargetType="ListViewItem">
<ContentControl Content="{Binding }"></ContentControl>
</ControlTemplate>
</ListView.Resources>-->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="White" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!--<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true" />
<Condition Property="Selector.IsSelectionActive" Value="true" />
</MultiTrigger.Conditions>
<Setter Property="Template" Value="{StaticResource SelectedTemplate}" />
</MultiTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>-->
</ItemsControl>
</Grid>
<StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Orientation="Horizontal">
<ComboBox x:Name="Baseforms"></ComboBox>
<ComboBox x:Name="CrystalGroups"></ComboBox>
</StackPanel>
</Grid>
Code behind (updated)
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty ShapesProperty = DependencyProperty.Register(
"Shapes", typeof (ObservableCollection<Shape>), typeof (MainWindow),
new PropertyMetadata(default(ObservableCollection<Shape>)));
public ObservableCollection<Shape> Shapes
{
get { return (ObservableCollection<Shape>) GetValue(ShapesProperty); }
set { SetValue(ShapesProperty, value); }
}
public ObservableCollection<string> Baselist = new ObservableCollection<string> {"a", "b", "c"};
public ObservableCollection<string> Crystallist = new ObservableCollection<string>{"aa", "bb", "cc"};
public ObservableCollection<Shape> Shapelist = new ObservableCollection<Shape>();
private SolidColorBrush _originalColorBrush = Brushes.Tomato;
private SolidColorBrush _selectedColorBrush;
private double _diameter;
public MainWindow()
{
_diameter = 50d;
this.ResizeMode = System.Windows.ResizeMode.CanMinimize;
Shapes = new ObservableCollection<Shape>();
InitializeComponent();
InitializeLists(Baseforms, CrystalGroups);
}
private void InitializeLists(ComboBox Baseforms, ComboBox CrystalGroups)
{
Baseforms.ItemsSource = Baselist;
CrystalGroups.ItemsSource = Crystallist;
Shape Circle = new Ellipse();
Circle.Stroke = System.Windows.Media.Brushes.Black;
Circle.Fill = System.Windows.Media.Brushes.DarkBlue;
Circle.HorizontalAlignment = HorizontalAlignment.Left;
Circle.VerticalAlignment = VerticalAlignment.Center;
Circle.Width = 50;
Circle.Height = 50;
Shapelist.Add(Circle);
}
private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
{
var inputElement = sender as IInputElement;
if (inputElement == null) return;
var point = e.GetPosition(inputElement);
Shape shape = new Ellipse
{
Stroke = Brushes.Black,
Fill = _originalColorBrush,
Width = _diameter,
Height = _diameter
};
var byX = point.X - _diameter / 2d;
var byY = point.Y - _diameter / 2d;
var existingShape = Shapes.FirstOrDefault(shapeToCheck =>
{
var data = shapeToCheck.Tag as ShapeDataPresentation;
if (data == null) return false;
var res = data.OriginalRectAroundShape.IntersectsWith(new Rect(point,point));
return res;
});
if (existingShape == null)
{
var shapeDataPresentation = new ShapeDataPresentation { Name = string.Format("Ox:{0}, Oy:{1}", point.X.ToString("##.###"), point.Y.ToString("##.###")), OriginalRectAroundShape = new Rect(new Point(byX, byY), new Size(_diameter, _diameter)) };
shape.Tag = shapeDataPresentation;
shape.ToolTip = new ToolTip{Content = shapeDataPresentation.Name};
var translateTransform = new TranslateTransform(byX, byY);
shape.RenderTransform = translateTransform;
Shapes.Add(shape);
}
else
{
if (DetailsList.SelectedItems.Contains(existingShape) == false)
{
DetailsList.SelectedItems.Clear();
DetailsList.SelectedItems.Add(existingShape);
}
}
}
private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var currentSelected = e.AddedItems.OfType<Shape>().ToList();
var prevSelected = e.RemovedItems.OfType<Shape>().ToList();
if (currentSelected.Count > 0)
{
currentSelected.ForEach(shape =>
{
_selectedColorBrush = Brushes.CadetBlue;
shape.Fill = _selectedColorBrush;
});
}
if (prevSelected.Count > 0)
{
prevSelected.ForEach(shape =>
{
shape.Fill = _originalColorBrush;
});
}
}
}
public class ShapeDataPresentation
{
public string Name { get; set; }
public Rect OriginalRectAroundShape { get; set; }
}
How it is looks like
Summary:
Here you can create item by mouse click on canvas, mouse down handled
in code (UIElement_OnMouseDown).
Allowed selection and multi-selection, each time you make selection it will be handled in code (Selector_OnSelectionChanged).
But it is better to use the MVVM based approach to work in wpf.
Regards.

Error when i use storyboard in windows phone 8?

I'm working on a Windows Phone app and i create storyboard that changes position an image.But i have an error.
An exception of type 'System.InvalidOperationException' occurred in System.Windows.ni.dll but was not handled in user code storyboard
This is my code:
XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" MouseMove="Mouse_Move">
<Grid.Resources>
<Storyboard x:Name="sbimg">
<PointAnimation x:Name="animationimg" Duration="0:0:0.1"
Storyboard.TargetName="earimg" />
</Storyboard>
</Grid.Resources>
<Image x:Name="earimg" Height="30" Width="30"
Source="1.png" Margin="0,0,426,577">
</Image>
</Grid>
And C#:
private void Mouse_Move(object sender, System.Windows.Input.MouseEventArgs e)
{
double pointX = e.GetPosition(null).X;
double pointY = e.GetPosition(null).Y;
Point mypoint = new Point(pointX,pointY);
animationimg.To = mypoint;
sbimg.Begin();
}
To accomplish this task I suggest to use a Canvas as LayoutRoot and a GestureListner from Windows Phone Toolkit to catch user gestures. Your XAML should looks like this
<Canvas x:Name="LayoutRoot"
Background="Transparent">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener
x:Name="SurfaceGestureListner"
Tap="SurfaceGestureListner_OnTap"
DragDelta="GestureListnerDragDelta"/>
</toolkit:GestureService.GestureListener>
<Image
x:Name="MyImage"
Source="/Assets/ApplicationIcon.png" Height="100" Width="100">
<Image.RenderTransform>
<TranslateTransform x:Name="TranslateTransform"/>
</Image.RenderTransform>
</Image>
</Canvas>
And in code behind
private Storyboard GenerateMoveAnimation(double x, double y)
{
var xAnimation = new DoubleAnimation
{
From = TranslateTransform.X,
To = x
};
var yAnimation = new DoubleAnimation
{
From = TranslateTransform.Y,
To = y
};
Storyboard.SetTarget(xAnimation, TranslateTransform);
Storyboard.SetTargetProperty(xAnimation, new PropertyPath("X"));
Storyboard.SetTarget(yAnimation, TranslateTransform);
Storyboard.SetTargetProperty(yAnimation, new PropertyPath("Y"));
var str = new Storyboard();
str.Children.Add(xAnimation);
str.Children.Add(yAnimation);
return str;
}
private void GestureListnerDragDelta(object sender, DragDeltaGestureEventArgs e)
{
var point = e.GetPosition(LayoutRoot);
GenerateMoveAnimation(point.X, point.Y).Begin();
}
private void SurfaceGestureListner_OnTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
{
var point = e.GetPosition(LayoutRoot);
GenerateMoveAnimation(point.X, point.Y).Begin();
}

Set selection to view box

Hello I have some buttons randomly assigned in my WPF application like so:
partial class Window1
{
private void button3_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("action 3");
}
void button2Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("action 2");
}
void button1Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("action 1");
}
public Window1()
{
this.InitializeComponent();
populateButtons();
}
public void populateButtons()
{
double xPos;
double yPos;
Random ranNum = new Random();
foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = 100;
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(200);
yPos = ranNum.Next(250);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += routedEventHandler;
LayoutRoot.Children.Add(foo);
}
}
}
}
I set the area in which to populate the buttons like so:
int xPos;
int yPos;
xPos = ranNum.Next(239);
yPos = ranNum.Next(307);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
What I would prefer to do now is set this area with a view box named viewbox1 (original eh!) ;)
Is there a way to do this in the code behind?
XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xml:lang="en-US"
x:Class="DynamicButtons.Window1"
x:Name="Window"
Title="Dynamic Buttons"
WindowState="Normal" WindowStyle="None" AllowsTransparency="True" Background="Transparent"
Width="840" Height="600" Icon="shape_group.png">
<Window.Resources>
<Style x:Key="CurvedButton" BasedOn="{x:Null}" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<ControlTemplate.Resources>
<Storyboard x:Key="OnMouseMove1">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFFFFFF"/>
<SplineColorKeyFrame KeyTime="00:00:00.3000000" Value="#7CE1DBDB"/>
</ColorAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
<SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="1.66"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
<SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="1.66"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="OnMouseLeave1">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
<SplineDoubleKeyFrame KeyTime="00:00:00.8000000" Value="1.78"/>
<SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
<SplineDoubleKeyFrame KeyTime="00:00:00.8000000" Value="1.78"/>
<SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="OnClick1">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.2000000" Value="#FFFFFFFF"/>
<SplineColorKeyFrame KeyTime="00:00:00.3000000" Value="#BFA0D1E2"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Grid>
<Rectangle RenderTransformOrigin="1,1" Fill="#3FFFFFFF" Stroke="{x:Null}" RadiusX="11" RadiusY="11" x:Name="rectangle">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
</Grid>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click">
<BeginStoryboard x:Name="OnClick1_BeginStoryboard" Storyboard="{StaticResource OnClick1}"/>
</EventTrigger>
<EventTrigger RoutedEvent="Mouse.MouseLeave">
<BeginStoryboard x:Name="OnMouseLeave1_BeginStoryboard" Storyboard="{StaticResource OnMouseLeave1}"/>
</EventTrigger>
<EventTrigger RoutedEvent="FrameworkElement.Loaded"/>
<EventTrigger RoutedEvent="Mouse.MouseEnter">
<BeginStoryboard x:Name="OnMouseMove1_BeginStoryboard" Storyboard="{StaticResource OnMouseMove1}"/>
</EventTrigger>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF3F3F3" Offset="0"/>
<GradientStop Color="#FFEBEBEB" Offset="0.5"/>
<GradientStop Color="#FFDDDDDD" Offset="0.5"/>
<GradientStop Color="#E1CDCDCD" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded"/>
</Window.Triggers>
<Grid x:Name="LayoutRoot">
<Grid Name="MainLayoutGrid" Background="#2b2b2b">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="4" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="4" />
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="4" />
</Grid.RowDefinitions>
<Grid Grid.Column="1" Grid.Row="1" Name="TitleGrid">
<Grid.RowDefinitions>
<RowDefinition Height="2"/>
<RowDefinition Height="*"/>
<RowDefinition Height="4"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="4"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Name="ImageIcon" Stretch="Uniform"/>
<TextBlock Grid.Column="2" Name="Titleblk" Foreground="White">Wanna be Title</TextBlock>
</Grid>
<Grid Grid.Row="0" Grid.Column="2" Grid.RowSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Name="btnMin" Grid.Column="1" Grid.ColumnSpan="2" Margin="8,4,42,-4">
<Button.RenderTransform>
<ScaleTransform ScaleX="0.8" ScaleY="0.8"></ScaleTransform>
</Button.RenderTransform>
<Button.Clip>
<RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,18,20" />
</Button.Clip>
</Button>
<Button Name="btnMax" Grid.Column="2" Margin="2,4,23,-4">
<Button.RenderTransform>
<ScaleTransform ScaleX="0.8" ScaleY="0.8"></ScaleTransform>
</Button.RenderTransform>
<Button.Clip>
<RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,18,20" />
</Button.Clip>
</Button>
<Button Name="btnClose" Grid.Column="2" Margin="24,0,6,0" BorderBrush="#00000000" BorderThickness="0" ClickMode="Press" Foreground="#00000000" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" OpacityMask="#82F8F8F8" VerticalAlignment="Stretch" VerticalContentAlignment="Center">
<Button.Clip>
<RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,20,20" />
</Button.Clip>
</Button>
</Grid>
</Grid>
<Grid Grid.Column="1" Grid.Row="2">
<Grid.Background>
<LinearGradientBrush EndPoint="0.484,0.543" StartPoint="0.478,0.009">
<GradientStop Color="Gray" Offset="1"/>
<GradientStop Color="DarkGray" Offset="0"/>
</LinearGradientBrush>
</Grid.Background>
<UniformGrid>
<Viewbox Height="364" Name="viewbox1" Width="363" VerticalAlignment="Stretch" Margin="6,0,441,164" />
</UniformGrid>
</Grid>
</Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--<Canvas Height="284" HorizontalAlignment="Left" Margin="457,66,0,0" Name="canvas1" VerticalAlignment="Top" Width="300" />-->
</Grid>
</Window>
Full Code:
namespace DynamicButtons
{
partial class Window1
{
void button3_Click(object sender, RoutedEventArgs e)
{
if (e.RoutedEvent == FrameworkElement.LoadedEvent)
{
ToolTip t = new ToolTip();
t.Content = "Something helpful";
((Button)sender).ToolTip = t;
((Button)sender).Content = "Hello";
return;
}
MessageBox.Show("Hello you punk");
}
void button2Click(object sender, RoutedEventArgs e)
{
//ToolTip t = new ToolTip();
//t.Content = "Something helpful";
//((Button)sender).ToolTip = t;
//MessageBox.Show("action 2");
}
void button1Click(object sender, RoutedEventArgs e)
{
//ToolTip t = new ToolTip();
//t.Content = "Something helpful";
//((Button)sender).ToolTip = t;
////Button b = new Button();
//((Button)sender).Content = "Hello";
////b.ToolTip = t;
//MessageBox.Show("action 1");
}
public Window1()
{
this.InitializeComponent();
populateButtons();
}
public void populateButtons()
{
double xPos;
double yPos;
UniformGrid grid = new UniformGrid();
Viewbox viewBox = new Viewbox();
viewBox.Name = "viewbox1";
viewBox.Stretch = Stretch.Fill;
viewBox.Child = grid;
LayoutRoot.Children.Add(viewBox);
Random ranNum = new Random();
foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = 100;
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(100);
yPos = ranNum.Next(150);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += routedEventHandler;
foo.Loaded += routedEventHandler;
grid.Children.Add(foo);
}
}
To add the buttons to a ViewBox you can just do this:
public void populateButtons()
{
double xPos;
double yPos;
UniformGrid grid = new UniformGrid();
viewbox1.Child = grid;
Random ranNum = new Random();
foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = 100;
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(200);
yPos = ranNum.Next(250);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += routedEventHandler;
grid.Children.Add(foo);
}
}
What is your reasoning for using a Viewbox? Is it for stretch and scale reasons?
I recommend using a Canvas and then you can set your Canvas.Left and Canvas.Top values similarly to how you set xPos and yPos.
Then if you wish to have the stretch / scale features of the Viewbox, you could put the Canvas you created as the child of the Viewbox.
UPDATE: to get the ActualHeight and ActualWidth values of the canvas during runtime you can add an event handler for SizeChanged (easy to do within the XAML but not too hard within code) to handle the change in height/width value during runtime. Here's the code solution:
bool initialized = false; // Should be located in class definition for your window
// ex. within "public partial class WindowName : Window
canvas.SizeChanged += new SizeChangedEventHandler(canvas_SizeChanged);
// Can be located in constructor for window
// ie. public MainWindow() { /* put it right here */ }
then the definition for the event handler can be as follows: (this only creates one button but would work with your for loop.)
Location update This definition below can be located within the class def for your window, but below the definition for the boolean variable "initialized". (ex. w/in "public partial class WindowName : Window")
private void canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (initialized == false) // so this only happens once.
{
int sizeValue = 100;
Random ranNum = new Random();
int modHeight = System.Convert.ToInt32(canvas.ActualHeight)-sizeValue;
int modWidth = System.Convert.ToInt32(canvas.ActualWidth)-sizeValue;
Button foo = new Button();
canvas.Children.Add(foo);
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(239) % modWidth;
yPos = ranNum.Next(307) % modHeight
Canvas.SetLeft(foo, xPos);
Canvas.SetTop(foo, yPos);
initialized = true;
}
}
Or, if you know what size your canvas is going to be you can just manually set modHeight and modWidth to the pixel value of your choice and not have to deal with the event handler.

Categories

Resources