Set focus on a Canvas created programatically, in Windows Phone 8.1 - c#

I have an image of a map inside a scrollviewer and, using 2 canvas, I place a little square (or a map pin image) after the user selects where they are.
Now, since they do not "click" on the map to do so, but they select their location from a list, I need to make that square the center of the view, in the scrollviewer, once they see the map.
In my xaml, I have just a few things since, all the information, comes from an API
<Grid x:Name="firstFloor" Margin="0,50,0,0" Visibility="Visible">
<ScrollViewer x:Name="pruebaScrollViewer1" BringIntoViewOnFocusChange="True" ZoomMode="Enabled" HorizontalScrollBarVisibility="Auto" HorizontalScrollMode="Enabled">
<Grid x:Name="myMap1stFloor">
</Grid>
</ScrollViewer>
</Grid>
and in code behind I have
private void showStorePosition2(string map_id, string name, int width, int height, int tile, int x, int y)
{
IdOfMapWhereIAm = map_id;
if (map_id == "10")
{
if (!_primerPiso)
{
//my parent canvas is defined globally
//the width and height of it come from API
myParentCanvas.Width = width;
myParentCanvas.Height = height;
myParentCanvas.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center;
myParentCanvas.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
Debug.WriteLine(width);
ImageBrush pushpin = new ImageBrush();
pushpin.ImageSource = new BitmapImage(new Uri("ms-appx:/Imagenes/mappin.png", UriKind.Absolute));
TextBlock storeName = new TextBlock();
storeName.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
storeName.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
storeName.TextAlignment = TextAlignment.Center;
storeName.FontFamily = new Windows.UI.Xaml.Media.FontFamily("Open Sans");
storeName.Height = 20;
storeName.Width = Double.NaN;
storeName.FontSize = 15;
storeName.Text = name;
storeName.Margin = new Thickness(-20, -20, 0, 0);
storeName.TextWrapping = TextWrapping.Wrap;
storeName.Foreground = new SolidColorBrush(Colors.Black);
Canvas myInititialStore = new Canvas();
myInititialStore.Background = pushpin;
myInititialStore.Height = 13;
myInititialStore.Width = 13;
Canvas.SetTop(myInititialStore, (y) * tile);
Canvas.SetLeft(myInititialStore, (x) * tile);
myInititialStore.Children.Add(storeName);
myParentCanvas.Children.Add(myInititialStore);
myMap1stFloor.Children.Add(myParentCanvas);
}
}
}
I was thinking about giving myInitialStore a dependency property, setting the focusProperty, but I do not know how to do it either.

In case someone has the same problem I had, I found a way to "focus" on the Canvas I needed to:
Instead of trying to do so, I changed the view in the scrollviewer, using the Canvas values, that way, when the Canvas is loaded inside the scrollviewer, this last one moves automatically to where the Canvas is located:
ScrollViewer1.ChangeView(((initialStore_x * tileMapToGo) - (widthMapToGo / tileMapToGo)), ((initialStore_y * tileMapToGo) - (heightMapToGo / tileMapToGo)), 1, false);
Hope it helps someone. Regards

Related

UWP show Fullscreen Popup, ContentDialog or Flyout

I need to display a full screen dialog (in application window boundaries) in my UWP application, but can't seems to make it work. I tried with :
ContentDialog only shows vertically stretched with FullSizeDesired="True"
Popup, even trying to set the width and height in code behind its not working
Flyout Placement="Full" only stretch it vertically just like the contentdialog
Can't believe I spend so much time on that thing :(
Thanks
Have you tried something like this:
var c = Window.Current.Bounds;
var g = new Grid
{
Width = c.Width,
Height = c.Height,
Background = new SolidColorBrush(Color.FromArgb(0x20, 0, 0, 0)),
Children =
{
new Rectangle
{
Width = 100,
Height = 100,
Fill = new SolidColorBrush(Colors.White),
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 3
}
}
};
var p = new Popup
{
HorizontalOffset = 0,
VerticalOffset = 0,
Width = c.Width,
Height = c.Height,
Child = g
};
p.IsOpen = true; // open when ready
You should see a semi-transparent overlay with a white rectangle in the middle of your screen.
To make a popup Fullscreen I did the following. Hope this helps.
I have a user control I wanted to show as a popup. Its name "URLUserControl"
Step 1: UI of the UC (Just the first bit. Not complete code)
<UserControl>
<Grid>
<Popup x:Name="MPopup" VerticalAlignment="Center">
<Grid x:Name="MainGrid">
Step 2: UC constructor adds the following
private void InitURLUserControl()
{
MPopup.IsOpen = true;
Window.Current.SizeChanged += Current_SizeChanged;
MainGrid.Width = Window.Current.Bounds.Width;
MainGrid.Height = Window.Current.Bounds.Height;
}
Step 3:
private void Current_SizeChanged(object sender, WindowSizeChangedEventArgs e)
{
MainGrid.Width = Window.Current.Bounds.Width;
MainGrid.Height = Window.Current.Bounds.Height;
}
The above code will help the popup to be the center of the screen and display in fullscreen in size. Check it out. Happy coding!

c# Relative position of elements in Windows Form

I try to create simple app with 2 columns using SpliterContainer and control panel with buttons. And I would like that on every screen it will look good. That's why I decided to use relative position of elements.
I read documentation and different forums, but I get something strange. Second column of splitter doesn't appear at all.
Please, can you help me find the reason of that problem?
private void Form1_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
//set form size
this.Size = new Size(screenWidth, screenHeight);
//set button panel size
const double percentOfHeightPanel = 0.05;
int heightOfPanelButton = Convert.ToInt32(screenHeight * percentOfHeightPanel);
this.panel_button.Size = new System.Drawing.Size(screenWidth, heightOfPanelButton);
this.panel_button.Location = new Point(0, 0);
//set splitContainer size
int widthOfContainer = Convert.ToInt32(0.5 * screenWidth);
int heightOfContainers = Convert.ToInt32(screenHeight * (0.95));
splitContainer1.Panel1.MinimumSize = new Size(widthOfContainer, heightOfContainers);
splitContainer1.Panel2.MinimumSize = new Size(widthOfContainer, heightOfContainers);
splitContainer1.Location = new Point(0, heightOfPanelButton);
//this.splitContainer1.Panel2MinSize = screenWidth - widthOfContainer;
//set textBox size
this.textBox1.Multiline = true;
this.textBox1.Location = new Point(0, heightOfPanelButton);
this.textBox1.MinimumSize = new System.Drawing.Size(widthOfContainer, heightOfContainers);
this.textBox2.Multiline = true;
this.textBox2.Location = new Point(widthOfContainer, heightOfPanelButton);
this.textBox1.MinimumSize = new System.Drawing.Size(widthOfContainer, heightOfContainers);
}
If you want two have two splitter panels of the same size set
splitContainer1.SplitterDistance =
(splitContainer1.Width - splitContainer1.SplitterWidth) / 2;
Then set
splitContainer1.IsSplitterFixed = true;
You can set these two properties manually at design time. The user will then not be able to resize the panels and the panels will automatically resize to be of same size.
Consider using a TableLayoutPanel instead.
If further, the two sides should look the same, place your controls on a UserControl and place two instances of them into the two panels with a docked property set to Fill.

Transparent canvas, with opaque elements

I'm trying to simulate an Android UI element that unfortunately doesn't exist in Windows 7 phone: ListPreference
I thought about using a Popup, that would take exactly the whole screen (to simulate a modal window).
So the popup would be made of the following elements:
Popup -> Canvas -> Border -> StackPanel -> RadioButtons
The Canvas would be fully transparent (or lightly whitish to clearly show that the element underneath aren't available)
The border would be made so it only big enough to contain all the RadioButtons
Then the StackPanel would be opaque and black.
Unfortunately, if I make the bottom canvas transparent, all children elements are also transparent. I can only make the elements more transparent.
The way transparency works is slightly different than with Android or iPhone (where it's quite easy to have a parent fully transparent, but opaque children).
Is there a way to make a parent fully transparent with the children opaque?
Or maybe someone could suggest another way to simulate a modal window.
Who knows, maybe someone even developed a ListPreference-like UIElement :)
Thank you
Here is how I ended up doing it.
It works in a similar fashion as ListPreference on Android. The constructor takes a string, an array of string and an int indicating which is the default value
When the windows is closed, the delegate Dismissed is called..
So you call it like so:
string[] choices = { "Choice 1", "Choice 2", "Choice3" };
ListPreference lp = new ListPreference("name", choices, 1);
lp.dismissed += new ListPreferences.DismissedHandler(lp_Dismissed);
the code:
public class ListPreference
{
Popup p;
string Name;
int oldValue;
public delegate void DismissedHandler(string name, bool changed, int newvalue);
public event DismissedHandler Dismissed;
public bool IsOpen
{
get
{
return p.IsOpen;
}
set
{
p.IsOpen = value;
}
}
public ListPreference(string name, Array elements, int default_value)
{
p = new Popup();
Name = name;
Dismissed = null;
oldValue = default_value;
double height = (App.Current.RootVisual as FrameworkElement).ActualHeight;
double width = (App.Current.RootVisual as FrameworkElement).ActualWidth;
p.VerticalOffset = SystemTray.IsVisible ? 32.0 : 0.0;
p.Height = height;
p.Width = width;
Canvas canvas = new Canvas();
SolidColorBrush colorBrush = new SolidColorBrush(Colors.Black);
colorBrush.Opacity = 0.75;
//Color.FromArgb(0xff, 0x8a, 0x8a, 0x8a));
canvas.Background = colorBrush;
//canvas.Opacity = 0.765;
canvas.Height = height;
canvas.Width = width;
p.Child = canvas;
Border border = new Border();
border.Width = width - 50.0 * 2.0;
border.BorderBrush = new SolidColorBrush(Colors.LightGray);
border.BorderThickness = new Thickness(5.0);
border.Background = new SolidColorBrush(Colors.Black);
canvas.Children.Add(border);
StackPanel panel2 = new StackPanel();
panel2.Orientation = System.Windows.Controls.Orientation.Vertical;
int i = 0;
foreach (string val in elements)
{
RadioButton radio1 = new RadioButton();
radio1.GroupName = "group1";
radio1.Content = val;
if (i == default_value)
radio1.IsChecked = true;
int j = i;
radio1.Click += (sender, args) => radio1_Checked(radio1, j);
i++;
panel2.Children.Add(radio1);
}
Button button1 = new Button();
button1.Background = new SolidColorBrush(Colors.Black);
button1.Foreground = new SolidColorBrush(Colors.White);
button1.Opacity = 1.0;
button1.Content = "Cancel";
button1.Margin = new Thickness(5.0);
button1.Click += new RoutedEventHandler(closeButton_Click);
panel2.Children.Add(button1);
border.Child = panel2;
// Open the popup.
p.IsOpen = true;
p.UpdateLayout();
border.Height = panel2.DesiredSize.Height + 5.0 * 2.0;
border.SetValue(Canvas.TopProperty, (height - border.Height) / 2.0);
border.SetValue(Canvas.LeftProperty, (width - border.Width) / 2.0);
p.UpdateLayout();
}
void closeButton_Click(object sender, RoutedEventArgs e)
{
// Close the popup.
p.IsOpen = false;
if (Dismissed != null)
{
Dismissed(Name, false, -1);
}
}
void radio1_Checked(object sender, int idx)
{
p.IsOpen = false;
if (Dismissed != null)
{
Dismissed(Name, idx != oldValue, idx);
}
}
}
I would suggest creating a Usercontrol that would do what you need. Set the LayoutRoot grid's background to PhoneSemitransparentBrush or changing the opacity will change the child element's opacity as well. Then your child elements can have any opacity you'd like. You can add this control as a child to the popup. Additionally, you can add doubleanimation to the popup with the opened and closed event triggers. Change the design height of the UserControl to 480x760 to simulate full page.
To answer your question. Using resources like PhoneSemitransparentBrush and TransparentBrush for the Canvas background is one of your options. Opacity will change the opacity of the whole UIElement including its children.

Dynamic Viewbox not Stretching

In my earlier example of Input Box, I have a window variable. I created some controls(Textbox, Label, Buttons). Parent of these controls is canvas. Parent of canvas is a ViewBox (because ViewBox can only contain one child) and parent of ViewBox is the window.
So hierarchy is like Window->Viewbox->Canvas-> Controls. All these control creation and parenting is done dynamically.
winInputDialog = new Window();
lblPrompt = new Label();
btnOK = new Button();
btnCancel = new Button();
txtInput = new TextBox();
cvContainer = new Canvas();
VB = new Viewbox();
//
// lblPrompt
//
lblPrompt.Background = new SolidColorBrush(SystemColors.ControlColor);
lblPrompt.FontFamily = new FontFamily("Microsoft Sans Serif");
lblPrompt.FontSize = 12;
lblPrompt.Background = new SolidColorBrush(Colors.Transparent);
lblPrompt.FontStyle = FontStyles.Normal;
lblPrompt.Margin = new Thickness(8, 9, 0, 0);
lblPrompt.Name = "lblPrompt";
lblPrompt.Width = 302;
lblPrompt.Height = 82;
lblPrompt.TabIndex = 3;
//
// btnOK
//
btnOK.Margin = new Thickness(322, 8, 0, 0);
btnOK.Name = "btnOK";
btnOK.Width = 64;
btnOK.Height = 24;
btnOK.TabIndex = 1;
btnOK.Content = "OK";
btnOK.Click += new RoutedEventHandler(btnOK_Click);
//
// btnCancel
//
btnCancel.Margin = new Thickness(322, 40, 0, 0);
btnCancel.Name = "btnCancel";
btnCancel.Width = 64;
btnCancel.Height = 24;
btnCancel.TabIndex = 2;
btnCancel.Content = "Cancel";
btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
//
// txtInput
//
txtInput.Margin = new Thickness(8, 70, 0, 0);
txtInput.Name = "txtInput";
txtInput.Width = 379;
txtInput.Height = 25;
txtInput.TabIndex = 0;
//
//Canvas
//
double width = System.Windows.SystemParameters.PrimaryScreenWidth / 3, height = System.Windows.SystemParameters.PrimaryScreenHeight / 4;
cvContainer.Height = height;
cvContainer.Width = width;
cvContainer.Children.Add(txtInput);
cvContainer.Children.Add(btnCancel);
cvContainer.Children.Add(btnOK);
cvContainer.Children.Add(lblPrompt);
cvContainer.ClipToBounds = true;
//
//ViewBox
//
VB.Stretch = Stretch.Fill;
VB.Child = cvContainer;
//
// InputBoxDialog
//
winInputDialog.Width = width;
winInputDialog.Height = height;
winInputDialog.Content = VB;
winInputDialog.Icon = new System.Windows.Media.Imaging.BitmapImage(new System.Uri(System.IO.Directory.GetCurrentDirectory() + #"\drop-box-icon.png"));
winInputDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
//winInputDialog.WindowStyle = WindowStyle.SingleBorderWindow;
winInputDialog.ResizeMode = ResizeMode.CanResizeWithGrip;
winInputDialog.Name = "InputBoxDialog";
I have set the width and height property of canvas equal to window. But why my screen look like this:
Why is there space between controls and window borders even though they are in viewbox. I even tried Cliptobounds but still the same.
If i set Viewbox height and width it does not stretch and behave unlike a Viewbox.
i want to set this screen dynamically. How?
Sample Project is at http://122.160.24.172/download/customer_data/InputBox_New.rar.
If you want your window to have a dynamic layout, why won't you use a dynamic container unlike Canvas which is static?
You could use a Grid like this -
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.8*"/>
<ColumnDefinition Width ="0.2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="Hello"/>
<Button Grid.Column="1" Content="Ok"/>
<Button Grid.Row="1" Grid.Column="1" Content="Cancel"/>
<TextBox Grid.Row="2" Grid.ColumnSpan="2" Text="Hello"/>
</Grid>
This way your window will layout itself when its size is changed.
You can still adjust the button size and margin if you'd like.
Don't use a Canvas unless you really need support for exact pixel coordination positioning layout.
Also: Why are you layouting your window programatically and not in XAML?

How to Control Z Order of Grids

I have the following code:
TextBlock tmp = new TextBlock
{
Text = displayText,
Foreground = new SolidColorBrush(Colors.Red),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
FontSize = 30
};
Grid grd = new Grid();
grd.Children.Add(tmp);
// grd.Background = new SolidColorBrush(Colors.LightGray);
Viewbox vb = new Viewbox();
vb.Child = grd;
vb.Width = width;
vb.Height = height;
DrawingCvs.Children.Add(vb);
Canvas.SetLeft(vb, xpos);
Canvas.SetTop(vb, ypos);
Canvas.SetZIndex(grd, 1000);
// we need a second grid for cosmetic reasons. Due to
// how the viewbox works, when we resize we lose the full
// width of the grid which has a textblock in it
Grid cosmeticGrd = new Grid
{
Width = width,
Height = height,
Background = new SolidColorBrush(Colors.LightGray)
};
DrawingCvs.Children.Add(cosmeticGrd);
Canvas.SetLeft(cosmeticGrd, xpos);
Canvas.SetTop(cosmeticGrd, ypos);
Canvas.SetZIndex(grd, 0);
What I want is for the Grid added first in the code to be above the grid added second. What is wrong with my Z-Index property setting here? Or is it something else?
InB4 Change the order you add them in the code--yes I realize this, but as a point of understanding I want to understand the ZIndex property.
Your first SetZindex call:
Canvas.SetZIndex(grd, 1000);
incorrectly applies the setting to the Grid instead of the Viewbox. It should be:
Canvas.SetZIndex(vb, 1000);
because the Viewbox is the child of the Canvas.
Likewise, your second SetZIndex call:
Canvas.SetZIndex(grd, 0);
is applied to the wrong Grid. It should be:
Canvas.SetZIndex(cosmeticGrd, 0);
In summary, the Canvas.ZIndex attached property affects the ordering of Canvas children.

Categories