Why does winforms CheckBox not meet top of container - winforms

I am trying to "pleasantly" align tops of control in a left-to-right flowpanel.
I have a checkbox and several numericUpDowns. BUT the checkbox always has some sort of margin or padding at the top. So, I have to add margn at top of numericUpDown to get them to line up.
This isn't ideal. Why can't I get checkBox to start directly below top of flowpanel, just like numericUpDown does?
public partial class Form1 : Form
{
public static FlowLayoutPanel ControlPanel;
public void CreateControls()
{
ControlPanel = new FlowLayoutPanel();
ControlPanel.SuspendLayout();
ControlPanel.FlowDirection = FlowDirection.LeftToRight;
ControlPanel.Height = 40;
ControlPanel.Width = this.flowLayoutPanel1.Width - 10;
ControlPanel.WrapContents = false;
ControlPanel.AutoScroll = true;
ControlPanel.Anchor = AnchorStyles.None;
ControlPanel.BorderStyle = BorderStyle.FixedSingle;
ControlPanel.Controls.Add(LabelWithText("LB", 60));
AddNumericUpDown("Ledge", 20, 0, 1m, -500m, 500m);
AddCheckBox("UseExit", "UseExit", false);
AddNumericUpDown("WrongLedge", 30, 0, 1m, -500m, 500m);
AddNumericUpDown("Max", 100000, 0, 100000m, 0m, 1000000m);
ControlPanel.ResumeLayout();
this.flowLayoutPanel1.Controls.Add(ControlPanel);
}
public Label LabelWithText(string text, int width)
{
Label label = new Label();
label.Text = text;
label.Width = width;
label.Top = 0;
return label;
}
public void AddCheckBox(string name, string text, bool initialValue)
{
CheckBox checkBox = new CheckBox();
checkBox.Name = name;
checkBox.Text = text;
checkBox.Checked = initialValue;
checkBox.Top = 0;
checkBox.Margin = new Padding(5,0,0,0);
checkBox.TextAlign = ContentAlignment.TopLeft;
checkBox.CheckAlign = ContentAlignment.TopLeft;
checkBox.ImageAlign = ContentAlignment.TopLeft;
ControlPanel.Controls.Add(checkBox);
}
public void AddNumericUpDown(string name, double initialValue, int decimalPlaces, decimal increment, decimal minimum, decimal maximum)
{
NumericUpDown numericUpDown = new NumericUpDown();
numericUpDown.DecimalPlaces = decimalPlaces;
numericUpDown.Increment = increment;
numericUpDown.Minimum = minimum;
numericUpDown.Maximum = maximum;
numericUpDown.Value = (decimal)initialValue;
numericUpDown.Name = name;
numericUpDown.Visible = true;
numericUpDown.Margin = new Padding(2);
numericUpDown.Top = 0;
numericUpDown.Width = 80;
ControlPanel.Controls.Add(LabelWithText(name, 70));
ControlPanel.Controls.Add(numericUpDown);
}
}

It's not the tops that are supposed to align. The baseline of the text is what's supposed to align between various controls. This is more evident if you use a larger font.

Related

unity array having 50 gameobjects but displays only 10 object

i have build a level menu with levels, i also created and empty array (GameObject[ ] lvlBut; )to store the level icons instantiated, but only 10 level icons are displayed on the screen where as i have 50 levels. for some reason its only taking 10 levels and i don’t t know where i have gone wrong. any suggestions?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UI;
using TMPro;
public class LevelSelector : MonoBehaviour{
public GameObject levelHolder;
public GameObject levelIcon;
public GameObject thisCanvas;
public int numberOfLevels = 50;
public Vector2 iconSpacing;
private Rect panelDimensions;
private Rect iconDimensions;
private int amountPerPage;
private int currentLevelCount;
int levelsUnlocked;
GameObject[] lvlBut;
void Start()
{
panelDimensions = levelHolder.GetComponent<RectTransform>().rect;
iconDimensions = levelIcon.GetComponent<RectTransform>().rect;
int maxInARow = Mathf.FloorToInt((panelDimensions.width + iconSpacing.x) / (iconDimensions.width + iconSpacing.x));
int maxInACol = Mathf.FloorToInt((panelDimensions.height + iconSpacing.y) / (iconDimensions.height + iconSpacing.y));
amountPerPage = maxInARow * maxInACol;
int totalPages = Mathf.CeilToInt((float)numberOfLevels / amountPerPage);
LoadPanels(totalPages);
}
void LoadPanels(int numberOfPanels)
{
GameObject panelClone = Instantiate(levelHolder) as GameObject;
PageSwiper swiper = levelHolder.AddComponent<PageSwiper>();
swiper.totalPages = numberOfPanels;
for (int i = 1; i <= numberOfPanels; i++)
{
GameObject panel = Instantiate(panelClone) as GameObject;
panel.transform.SetParent(thisCanvas.transform, false);
panel.transform.SetParent(levelHolder.transform);
panel.name = "Page-" + i;
panel.GetComponent<RectTransform>().localPosition = new Vector2(panelDimensions.width * (i - 1), 0);
SetUpGrid(panel);
int numberOfIcons = i == numberOfPanels ? numberOfLevels - currentLevelCount : amountPerPage;
LoadIcons(numberOfIcons, panel);
}
Destroy(panelClone);
}
void SetUpGrid(GameObject panel)
{
GridLayoutGroup grid = panel.AddComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(iconDimensions.width, iconDimensions.height);
grid.childAlignment = TextAnchor.MiddleCenter;
grid.spacing = iconSpacing;
}
void LoadIcons(int numberOfIcons, GameObject parentObject)
{
for (int i = 1; i <= numberOfIcons; i++)
{
currentLevelCount++;
GameObject icon = Instantiate(levelIcon) as GameObject;
icon.transform.SetParent(thisCanvas.transform, false);
icon.transform.SetParent(parentObject.transform);
icon.name = "Level " + i;
icon.GetComponentInChildren<TextMeshProUGUI>().SetText(currentLevelCount.ToString());
}
lvlBut = GameObject.FindGameObjectsWithTag("LevelButton");
levelsUnlocked = PlayerPrefs.GetInt("levelsUnlocked", 1);
for (int i = 0; i < lvlBut.Length; i++)
{
lvlBut[i].GetComponentInChildren<Button>().interactable = false;
}
for (int i = 0; i < levelsUnlocked; i++)
{
lvlBut[i].GetComponentInChildren<Button>().interactable = true;
}
}
}

dropdown error on device in codenameone

I am implementing drop-drown feature in my app. Its implemented using container with list of elements in it.
Suppose the drop down list has following items aa1, aa2, aa3, aa4 aa5 and so on. And if i search as 'aa' it displays items starting from 'aa', if I select aa5 from list, it takes aa1 and displays that. But whereas if I scroll the items and select its working fine. This problem occurring only on iOS device working perfectly fine on simulator.
the first picture depicts how drop down looks like, in second picture if I search 'ee', it gives list of items starting with 'ee'. If I select 'ee5', it sets to ee1 as shown in picture 3. Problem only on device. Any workaround for this?
So, please let me know whats the issue with this.
Thanks
[![enter image description here][1]][1]
private CustomList itemList;
class CustomList extends List {
int startYPos = -1;
long lastDiff = 0;
Timer t = null;
int draggingState = 0;
public CustomList() {
this.setTensileDragEnabled(false);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(final ActionEvent evt) {
final Runnable rn = new Runnable() {
public void run() {
// Create and show a dialog to allow users to make a selection.
final UiBuilder uib = dm.UiBuilder();
dialog = (Dialog) uib.createContainer(DESIGNER_NAME_DIALOG_COMBOBOX_CONTAINER);
GenericSpinner itemSpinner = (GenericSpinner) uib.findByName(DESIGNER_NAME_DIALOG_COMBOBOX_GENERIC_SPINNER, dialog);
itemSpinner.setPreferredW(Display.getInstance().getDisplayWidth() * 4 / 5);
//remove from parent and replace with a linear list
Container parent = itemSpinner.getParent();
parent.removeComponent(itemSpinner);
// Add the searchable text field box
final TextField tf = (TextField)uib.findByName("Search", dialog);
tf.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
Object[] items = model.getFilteredItems(tf.getText());
itemList.setModel(new DefaultListModel(items));
}
});
itemList = new CustomList();
itemList.getAllStyles().setBgTransparency(0);
itemList.setItemGap(0);
parent.addComponent(BorderLayout.CENTER, itemList);
final String[] items = model.getItems();
itemList.setModel(new DefaultListModel(items));
itemList.getStyle().setMargin(10, 10, 10, 10);
itemList.setFireOnClick(true);
itemList.setLongPointerPressActionEnabled(false);
ActionListener list = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (model.isUserEditable() && model.getItemCount() > 0) {
int i = itemList.getSelectedIndex();
if (i > items.length - 1) {
return;
}
itemList.getModel().setSelectedIndex(i);
model.onUserDataEntered((String) itemList.getModel().getItemAt(i));
String textToDisplay = (String) itemList.getModel().getItemAt(i);
button.setText(textToDisplay);
}
dialog.dispose();
}
};
itemList.addActionListener(list);
CommonTransitions tran = CommonTransitions.createEmpty();
dialog.setTransitionInAnimator(tran);
dialog.setTransitionOutAnimator(tran);
itemList.setRenderer(new ListRenderer());
//related to dialog to show list of items
//how much space do we really need???
if (cellHeight == 0) {
int dip = Display.getInstance().convertToPixels(1);
int siz = 2;
if (Display.getInstance().isTablet()) {
siz = 4;
}
siz *= 2;
cellHeight = siz * dip;
}
int heightRequired = cellHeight * (items.length + 8);
//is this too much for the screen - we will use 3/4 of the screen height max
int availableHeight = Display.getInstance().getDisplayHeight() * 3;
availableHeight /= 4;
if (heightRequired > availableHeight) {
int topPos = Display.getInstance().getDisplayHeight() / 8;
int bottomPos = topPos + availableHeight;
dialog.show(topPos, topPos, 40, 40);
}
else {
int topPos = (Display.getInstance().getDisplayHeight() - heightRequired) / 2;
int bottomPos = topPos + heightRequired;
dialog.show(topPos, topPos, 40, 40);
}
}
};
}
}
//new code using Multibutton implementation
final String[] listItems = model.getItems();
Display.getInstance().callSerially(() ->{
multiButton= new MultiButton();
multiButton.setTextLine1(s);
dialog.add(multiButton);
multiButton.addActionListener(e -> Log.p("you picked " + multiButton.getSelectCommandText(), Log.ERROR));
}
dialog.revalidate();
});
I would recommend using a Container and simple layout search as demonstrated by code such as this. The code below was taken from the Toolbar javadoc:
Image duke = null;
try {
duke = Image.createImage("/duke.png");
} catch(IOException err) {
Log.e(err);
}
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
// this will take a while...
Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : cnts) {
MultiButton m = new MultiButton();
m.setTextLine1(c.getDisplayName());
m.setTextLine2(c.getPrimaryPhoneNumber());
Image pic = c.getPhoto();
if(pic != null) {
m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
} else {
m.setIcon(finalDuke);
}
hi.add(m);
}
hi.revalidate();
});
});
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);
hi.show();

2D over 3D anti-aliasing artifacts

We have 3D models in WPF and use a cursor made from a Canvas and some internal parts. We turn the HW cursor off and move the Canvas through MouseEvent. The issue is that there are terrible artifacts on the screen as you move from left to right (not nearly as bad right to left). I have played with snaptodevicepixels, Edge mode and nvidea AA settings but the only thing that "fixes" is setting edge mode to aliased for the 3dviewport - and we don't want that. I have even made the cursor completely transparent and it still leaves artifacts.
I broke out some of the code for demonstration. You can especially see the artifacts moving upper-left to lower-right.
Anyone think they can help me out here? I'm head banging and not in a good way. It's looking more like a bug in the AA code.
Thanks
T
FYI: I used some Petzold code here for the beach ball.
Bad AA BeachBall
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
namespace Cursoraa2
{
class Program : Window
{
[STAThread]
public static void Main() => new Application().Run(new Program());
public Program()
{
Width = 500;
Height = 500;
var grid = new Grid();
var viewport = new Viewport3D();
grid.Children.Add(viewport);
Content = grid;
//RenderOptions.SetEdgeMode(viewport,EdgeMode.Aliased);
DynamicCurosr.Start(grid, grid, 40, Color.FromArgb(40, 0x33, 0x33, 0xff), Colors.Blue);
MouseMove += MainWindow_MouseMove;
MakeBeachBallSphere(viewport);
}
private void MainWindow_MouseMove(object sender, MouseEventArgs e) => DynamicCurosr.Move(e.GetPosition(this));
public void MakeBeachBallSphere(Viewport3D viewport)
{
// Get the MeshGeometry3D from the GenerateSphere method.
var mesh = GenerateSphere(new Point3D(0, 0, 0), 1, 36, 18);
mesh.Freeze();
// Define a brush for the sphere.
var brushes = new Brush[6] { Brushes.Red, Brushes.Blue,
Brushes.Yellow, Brushes.Orange,
Brushes.White, Brushes.Green };
var drawgrp = new DrawingGroup();
for (var i = 0; i < brushes.Length; i++)
{
var rectgeo = new RectangleGeometry(new Rect(10 * i, 0, 10, 60));
var geodraw = new GeometryDrawing(brushes[i], null, rectgeo);
drawgrp.Children.Add(geodraw);
}
var drawbrsh = new DrawingBrush(drawgrp);
drawbrsh.Freeze();
// Define the GeometryModel3D.
var geomod = new GeometryModel3D
{
Geometry = mesh,
Material = new DiffuseMaterial(drawbrsh)
};
// Create a ModelVisual3D for the GeometryModel3D.
var modvis = new ModelVisual3D { Content = geomod };
viewport.Children.Add(modvis);
// Create another ModelVisual3D for light.
var modgrp = new Model3DGroup();
modgrp.Children.Add(new AmbientLight(Color.FromRgb(128, 128, 128)));
modgrp.Children.Add(new DirectionalLight(Color.FromRgb(128, 128, 128), new Vector3D(2, -3, -1)));
modvis = new ModelVisual3D {Content = modgrp};
viewport.Children.Add(modvis);
// Create the camera.
var cam = new PerspectiveCamera(new Point3D(0, 0, 8), new Vector3D(0, 0, -1), new Vector3D(0, 1, 0), 45);
viewport.Camera = cam;
// Create a transform for the GeometryModel3D.
var axisangle = new AxisAngleRotation3D(new Vector3D(1, 1, 0), 180);
var rotate = new RotateTransform3D(axisangle);
geomod.Transform = rotate;
// Animate the RotateTransform3D.
//DoubleAnimation anima = new DoubleAnimation(360, new Duration(TimeSpan.FromSeconds(5)));
//anima.RepeatBehavior = RepeatBehavior.Forever;
//axisangle.BeginAnimation(AxisAngleRotation3D.AngleProperty, anima);
}
MeshGeometry3D GenerateSphere(Point3D center, double radius, int slices, int stacks)
{
// Create the MeshGeometry3D.
var mesh = new MeshGeometry3D();
// Fill the Position, Normals, and TextureCoordinates collections.
for (var stack = 0; stack <= stacks; stack++)
{
var phi = Math.PI / 2 - stack * Math.PI / stacks;
var y = radius * Math.Sin(phi);
var scale = -radius * Math.Cos(phi);
for (var slice = 0; slice <= slices; slice++)
{
var theta = slice * 2 * Math.PI / slices;
var x = scale * Math.Sin(theta);
var z = scale * Math.Cos(theta);
var normal = new Vector3D(x, y, z);
mesh.Normals.Add(normal);
mesh.Positions.Add(normal + center);
mesh.TextureCoordinates.Add(
new Point((double)slice / slices,
(double)stack / stacks));
}
}
// Fill the TriangleIndices collection.
for (var stack = 0; stack < stacks; stack++)
for (var slice = 0; slice < slices; slice++)
{
var n = slices + 1; // Keep the line length down.
if (stack != 0)
{
mesh.TriangleIndices.Add((stack + 0) * n + slice);
mesh.TriangleIndices.Add((stack + 1) * n + slice);
mesh.TriangleIndices.Add((stack + 0) * n + slice + 1);
}
if (stack != stacks - 1)
{
mesh.TriangleIndices.Add((stack + 0) * n + slice + 1);
mesh.TriangleIndices.Add((stack + 1) * n + slice);
mesh.TriangleIndices.Add((stack + 1) * n + slice + 1);
}
}
return mesh;
}
}
public static class DynamicCurosr
{
static public bool InSession { get; private set; }
private static Panel theCursor;
private static readonly ScaleTransform ScaleTransform = new ScaleTransform(1, 1);
private static readonly MatrixTransform MatrixTransform = new MatrixTransform(1, 0, 0, 1, 0, 0);
private static Color defaultFill = Color.FromArgb(20, 255, 255, 255);
private static Color fillFromUser;
private static double strokeFromUser = 0;
private static Color strokeColorFromUser = Colors.Black;
private static int centerDotSizeFromUser = 10; // need to get from user
private static double initialDiameter = double.NaN;
private static Panel cursorPanel;
private static Panel mousePanel;
public static bool Start(Panel cursorPanelIn, Panel mousePanelIn, double radius)
{
return Start(cursorPanelIn, mousePanelIn, radius, defaultFill);
}
public static bool Start(Panel cursorPanelIn, Panel mousePanelIn, double radius, Color fill, Color strokeColor = default(Color), double strokeSize = .16)
{
strokeColor = strokeColor == default(Color) ? Colors.Black : strokeColor;
strokeColorFromUser = strokeColor;
fillFromUser = fill;
strokeFromUser = strokeColor == default(Color) ? 0 : strokeSize;
initialDiameter = double.IsNaN(initialDiameter) ? radius * 2 : initialDiameter;
return Start(cursorPanelIn, mousePanelIn);
}
private static bool Start(Panel cursorPanelIn, Panel mousePanelIn)
{
if (InSession) return false;
cursorPanel = cursorPanelIn;
mousePanel = mousePanelIn;
var point = Mouse.GetPosition(cursorPanel);
theCursor = MakeACursor(theCursor, initialDiameter / 2);
InSession = true;
cursorPanel.Cursor = Cursors.None;
theCursor.Visibility = Visibility.Visible;
Move(point);
if (cursorPanel.Children.Contains(theCursor))
return false;
cursorPanel.Children.Add(theCursor);
Mouse.OverrideCursor = Cursors.None;
return true;
}
public static void Stop()
{
if (InSession)
{
Mouse.OverrideCursor = null;
theCursor.Visibility = Visibility.Collapsed;
cursorPanel.Children.Remove(theCursor);
InSession = false;
}
}
public static void Move(Point point)
{
if (InSession && theCursor.Visibility == Visibility.Visible)
{
var m = MatrixTransform.Matrix;
m.OffsetX = point.X - theCursor.Width / 2;
m.OffsetY = point.Y - theCursor.Height / 2;
MatrixTransform.Matrix = m;
theCursor.RenderTransform = MatrixTransform;
}
}
public static Panel MakeACursor(Panel theCursor, double radius, Color fillColorIn = default(Color), Color strokeColorIn = default(Color))
{
var strokeColor = new SolidColorBrush(strokeColorIn == default(Color) ? strokeColorFromUser : strokeColorIn);
if (theCursor == null)
{
theCursor = new Grid()
{
Width = radius * 2,
Height = radius * 2,
Background = null,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
RenderTransform = ScaleTransform,
RenderTransformOrigin = new Point(.5, .5),
};
var cursorElement = new Ellipse
{
Width = radius * 2,
Height = radius * 2,
Fill = new SolidColorBrush(fillColorIn == default(Color) ? fillFromUser : fillColorIn),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
StrokeThickness = strokeFromUser,
Stroke = strokeColor,
RenderTransformOrigin = new Point(.5, .5)
};
theCursor.Children.Add(cursorElement);
}
MakeCursorOverlay(theCursor, radius, strokeColor);
return theCursor;
}
public static void MakeCursorOverlay(Panel theCursor, double radius, SolidColorBrush strokeColor)
{
var save = theCursor.Children[0];
theCursor.Children.Clear();
theCursor.Children.Add(save);
var circle = new Ellipse
{
Width = centerDotSizeFromUser,
Height = centerDotSizeFromUser,
Fill = null,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
StrokeThickness = strokeFromUser,
Stroke = strokeColor,
RenderTransformOrigin = new Point(.5, .5)
};
theCursor.Children.Add(circle);
}
}
}

Getting new line in wpf

i am having arraylist.let say it contains 15 elements. I am adding these to stack panel. I need to add 3 elements per line. my code is below. I am getting either horizontal or verrtical.Let me know how to do this.
MainWindow w;
public ShopCart(MainWindow m,ArrayList _list)
{
InitializeComponent();
w = m;
int i = 1;
foreach (string cartitems in _list)
{
mystackpanel.Orientation = Orientation.Horizontal;
mystackpanel.Margin.Left.Equals(150);
Label lbl = new Label();
lbl.Name = "Label" + i;
lbl.Height = 30;
lbl.Width = 200;
lbl.Margin.Left.Equals(150);
//lbl.Margin.Top.Equals(150);
lbl.Content = cartitems.ToString();
mystackpanel.Children.Add(lbl);
i++;
int str = mystackpanel.Children.Count;
MessageBox.Show(Convert.ToString(str));
if (str%3 == 0)
{
Button btndelete = new Button();
btndelete.Content = "Delete";
btndelete.Width = 120;
btndelete.Height = 35;
mystackpanel.Children.Add(btndelete);
mystackpanel.Margin.Top.Equals(500);
}
}
Here is some sample code(assuming you already have a list of buttons, and will add outer stack panel to your main control) you can try, you may need to change few things as per your need:
List<Button> buttons = new List<Button>();
StackPanel panel = new StackPanel();
panel.Orientation = Orientation.Horizontal;
int count = 0;
StackPanel innerPanel = new StackPanel();
innerPanel.Orientation = Orientation.Vertical;
foreach (Button button in buttons)
{
innerPanel.Children.Add(button);
++count;
if (count % 3 == 0 && count != 0)
{
panel.Children.Add(innerPanel);
innerPanel = new StackPanel();
innerPanel.Orientation = Orientation.Vertical;
}
}
if (panel.Children.Contains(innerPanel) == false)
{
panel.Children.Add(innerPanel);
}
Although in my opinion the best way will be to have a Grid with n*n row and columns and add your buttons to respective row, columns.

Silverlight - Fill a rectangle with animation on mouseclick

I want to be able to fill a rectangle with an animation on leftmousebuttondown (this will later be changed to run on load).
My rectangles are drawn to a canvas in code behind based on the data that is passed (one rectangle per row of data)
At the moment they are filled with a static image but I want this Fill to be an animation, a spinner if I can.
I am very new to Silverlight and am not sure how to achieve this. Can someone point me in the right direction?
My code (part) so far.
XAML:
<Canvas x:Name="Grid" Background="LightGray"></Canvas>
CS:
public partial class ProductView : UserControl
{
Processing processingDialog = new Processing();
private int colsRequired = 0;
private int rowsRequired = 0;
private const int minSize = 5;
private int cellSize = 1;
public ProductView()
{
InitializeComponent();
}
public void UpdateGrid(ObservableCollection<Product> productList)
{
calculateRowsCols(productList);
drawGrid(productList);
}
public void calculateRowsCols(ObservableCollection<Product> productList)
{
int tileCount = productList.Count();
double tileHeight = Grid.ActualHeight;
double tileWidth = Grid.ActualWidth;
if (tileCount == 0)
return;
double maxSize = Math.Sqrt((tileHeight * tileWidth) / tileCount);
double noOfTilesHeight = Math.Floor(tileHeight / maxSize);
double noOfTilesWidth = Math.Floor(tileWidth / maxSize);
double total = noOfTilesHeight * noOfTilesWidth;
cellSize = (maxSize < minSize) ? minSize : Convert.ToInt32(maxSize);
while ((cellSize >= minSize) && (total < tileCount))
{
cellSize--;
noOfTilesHeight = Math.Floor(tileHeight / cellSize);
noOfTilesWidth = Math.Floor(tileWidth / cellSize);
total = noOfTilesHeight * noOfTilesWidth;
}
rowsRequired = Convert.ToInt32(Math.Floor(tileHeight / cellSize));
colsRequired = Convert.ToInt32(Math.Floor(tileWidth / cellSize));
}
private void drawCell(int row, int col, string label, Color fill)
{
Rectangle innertec = new Rectangle();
innertec.Height = cellSize * 0.7;
innertec.Width = cellSize * 0.9;
innertec.StrokeThickness = 1;
innertec.Stroke = new SolidColorBrush(Colors.Black);
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("Assets/loading.png", UriKind.Relative));
innertec.Fill = imageBrush;
Grid.Children.Add(innertec);
Canvas.SetLeft(innertec, (col * cellSize) + ((cellSize - innertec.Width) / 2));
Canvas.SetTop(innertec, row * cellSize + 4);
Border productLabelBorder = new Border();
Grid.Children.Add(productLabelBorder);
Canvas.SetLeft(productLabelBorder, col * cellSize);
Canvas.SetTop(productLabelBorder, row * cellSize);
TextBlock productLabel = new TextBlock();
productLabel.Margin = new Thickness(0, innertec.Height + 5, 0, 5);
productLabel.TextAlignment = TextAlignment.Center;
productLabel.TextWrapping = TextWrapping.NoWrap;
productLabel.TextTrimming = TextTrimming.WordEllipsis;
productLabel.MaxWidth = cellSize;
productLabel.Height = cellSize * 0.3;
productLabel.Width = cellSize;
productLabel.Text = label;
productLabel.HorizontalAlignment = HorizontalAlignment.Center;
productLabel.VerticalAlignment = VerticalAlignment.Center;
productLabel.FontSize = cellSize * 0.13;
ToolTipService.SetToolTip(productLabel, label);
productLabelBorder.Child = productLabel;
}
public void drawGrid(ObservableCollection<Product> data)
{
int dataIndex = 0;
Grid.Children.Clear();
for (int i = 0; i < rowsRequired; i++)
{
for (int j = 0; j < colsRequired; j++)
{
Product product = (dataIndex < data.Count) ? data.ElementAt(dataIndex) : null;
if (product != null)
{
drawCell(i, j, product.productName, Colors.White);
}
dataIndex++;
}
}
}
}
Any help anyone can give, even a pointer in the right direction would be great.
Thanks in advance
Try creating custom control which will encapsulate everything you want from rectangle to do.
you can add new VisualState "MouseDownState" and do required animatin in xaml.
Please let me know if you need more details regarding the implementation.
late simply add new control instead of rectangle.

Resources