How to change the position of dynamic buttons in wp8 c# - c#

In my windows phone application I am creating a dynamic button like below:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="24,0,0,0">
<TextBox x:Name="tb_groupname"
Height="90"
Background="White"
Margin="0,0,125,517"
Foreground="Blue" TextChanged="tb_groupname_TextChanged" GotFocus="tb_groupname_GotFocus" LostFocus="tb_groupname_LostFocus"/>
<Button x:Name="btn_groupname"
Content="Add"
Background="AliceBlue"
Foreground="Blue"
FontSize="25"
Width="120"
Height="90"
HorizontalAlignment="Right"
VerticalAlignment="Top" Click="btn_groupname_Click"></Button>
<ListBox x:Name="lb_groupofcontacts" ItemsSource="{Binding}" Margin="0,118,0,0">
</ListBox>
And below is the xaml.cs page code
private void btn_groupname_Click(object sender, RoutedEventArgs e)
{
if (tb_groupname.Text != string.Empty)
{
List<Button> buttons = new List<Button>();
Button btn = new Button();// Cast the control to Button.
btn.Content = tb_groupname.Text;
btn.Width = 200;
btn.Height = 200;
btn.Click += new RoutedEventHandler(btn_Click); // Add event to button.
buttons.Add(btn);
buttonName = tb_groupname.Text;
tb_groupname.Text = string.Empty;
lb_groupofcontacts.DataContext = buttons;
}
}
And add button into listbox lb_groupofcontacts but when I create another dynamic button it map onto the previous button means it not change the position of the button
And I want that
first button created on top left
second button created on top right
third button created on center left
forth button created on center right
fifth button created on bottom left
sixth button created on botton right
Kindly suggest me how do I change the position of the like above or if you know any other way to change the position of dynamic both then tell me, waiting for your reply.
Thanks.

First of all You are creating object of list into Button_click so every time it is creating new list and adds only new one button and taking that list as listbox's Content so you are not able to add Second Button.
You can set Position of Button Dynamically by:
btn.Margin = new Thickness(LEFT,TOP,RIGHT,BOTTOM);
OR
btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
btn.VerticalAlignment = System.Windows.VerticalAlignment.Center;

You can manipulate Button's position by setting its Margin property to different values ("0, 0" for the first button, "0, 200" for the second one and so on).
But that's not very good approach, the right way depends on what you need to do. I'd suggest to replace ListBox with Grid having 6 cells as the most simple decision.

Related

Howto add textboxes in runtime to a WPF Window in C#? [duplicate]

This question already has answers here:
Append a child to a grid, set it's row and column
(4 answers)
Closed 1 year ago.
I am learning algorithmics and C#, and I wanted to write a sudoku solver with some WPF interface.
I need 81 textboxes (one for each sudoku box) and I wanted to generate them with code and put them in array, instead of having 81 different objects.
I used the Visual Studio toolbox to drag and drop buttons in my main window. I also drag and dropped TextBoxes to get an idea how they would look like.
I don't find how to add the TextBoxes to the main Window, using a loop.
Here is the MainWindow.x.aml code :
<Window x:Class="SudokuPOO.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:SudokuPOO"
mc:Ignorable="d"
Title="Solveur de Sudoku" Height="260" Width="210">
<Grid>
<!--
<TextBox x:Name="T0" HorizontalAlignment="Left" Margin=" 10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="20"/>
<TextBox x:Name="T1" HorizontalAlignment="Left" Margin=" 30,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="20"/>
[ I DELETED STUFF HERE ]
-->
<Button Content="Résoudre" HorizontalAlignment="Left" Margin="10,210,0,0" VerticalAlignment="Top" Click="Resoudre"/>
<Button Content="Effacer tout" HorizontalAlignment="Left" Margin="75,210,0,0" VerticalAlignment="Top" Click="Effacer"/>
</Grid>
Here is the MainWindow.x.aml.cs I am trying to edit :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent(); // Was already here.
GenerateTextBoxes(); // I added that manually.
}
public void GenerateTextBoxes()
{
TextBox[] TextBoxes = new TextBox[5];
for (int i = 0; i<=4; i++)
{
TextBox TBox = new TextBox();
TBox.Margin = new Thickness(10+20*i, 10, 0, 0);
TBox.Text = i.ToString();
TBox.Width = 20;
TBox.Height = 20;
// this.Controls.Add(TBox); // Doesn't work.
this.Content = TBox; // Trouble here.
TextBoxes[i] = TBox;
}
}
}
I tried with only 5 textboxes to understand what is happening.
This code runs, it displays the MainWindow, but with only one TextBox with "4" in it.
My guess is that
this.Content = Tbox;
replaces all content of the window with only one TBox.
How do I a just add the Tbox ?
The XAML files suggests that a "TextBox" is inside a "Grid" that is inside the "MainWindow", but "this.Grid" doesn't exist, neither "MainWindow.Grid".
I tried stuff like "LayoutRoot.Children.Add", "this.Controls.Add", "this.Grid.Add" and so on, nothing works. Almost all the code I can find online related to TextBox in C# uses "Windows Forms" and not "WPF" and doesn't work in my case (like how to define an array of textboxes in c#? ).
Give the root panel in the XAML markup a name:
<Grid x:Name="grid">
...and then add the textboxes to the panel's Children collection:
grid.Children.Add(TBox);
Also note that that there might be better panels to use for layout instead of mocking around with margins: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/panels-overview?view=netframeworkdesktop-4.8

How to use a button x:Name or something to indicate button [duplicate]

This question already has answers here:
ICommand MVVM implementation
(4 answers)
Closed 1 year ago.
I have a problem. I have to do app for college, guitar emulator, my idea was to put each fret as a button, and implement the color change function to understand which fret (button) is clamped (pressed)
var button = (Button)sender;
_buttonLastPressed = button;
var parent = (Grid)button.Parent;
var index = parent.Children.IndexOf(strip1_1);
var str = Math.Floor((decimal)(index + 1) / 20);
for (int i = 0; i < 20; i++)
{
var element = (Button)parent.Children[i + Convert.ToInt32(str) * 20];
element.Background = Brushes.White;
}
button.Background = Brushes.Blue;
This option works well, but the problem arose that I do not know how to get some information from the button in order to use it on what sound to play (so that the program understands which button is pressed). I believe that it was possible to somehow use the DataContext, but I cannot imagine in my head how to do it more competently
For the tip, there are six strings, I decided to declare each string as grid, and in each grid there are 20 frets (buttons), you can hold down only one of all 20
XAML:
<Button x:Name="strip1_1" Content="" HorizontalAlignment="Left" Margin="2,1,0,0" VerticalAlignment="Top" Width="22" Height="4" Click="Strip1_Click" BorderBrush="Black"/>
<Button x:Name="strip1_2" Content="" HorizontalAlignment="Left" Margin="37,1,0,0" VerticalAlignment="Top" Width="22" Height="4" Click="Strip1_Click" BorderBrush="Black"/>
A possible solution could be to use the Click property of each button which references a different method.
<Button Click="DoSomething_OnClick"/>
and in the code-behind:
private void DoSomething_OnClick(object sender, RoutedEventArgs e)
{
// Your code here
}
You could use this to have 20 different methods. This way, you know exactly which button called which method.

UWP - How do I center a button?

I created a UWP solution and created a button. There are no problems with the buttons.
I do not know how to center the button in the window.
Code
StackPanel stackPanel1 = new StackPanel();
Button TestButton = new Button();
TestButton.Content = "Test";
stackPanel1.Children.Add(subscribeButton);
Window.Current.Content = stackPanel1;
This line is all you need.
TestButton.HorizontalAlignment = HorizontalAlignment.Center;
Changing the position of the button to half of the form's width and height will work.
Point point = new Point(this.Width / 2 - (button1.Width/2), this.Height / 2 - (button1.Height/ 2));
button1.Location = point;
The added - (button1.Width/2) is because the button's position is based on the upper right hand corner of the button, and not actually the center.
You can set HorizontalAlignment something like these inside the stackpanel...
<StackPanel Margin="10,0,0,0" Orientation="Horizontal" Grid.Column="0">
<TextBlock Grid.Column="1" Grid.Row="0" FontSize="16" HorizontalAlignment="Center">2. Draw a pattern</TextBlock>
<Button x:Name="DeleteSiteButton" Content="Delete Site"
HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Top" Click="DeleteSiteButton_Click"/>
<Button x:Name="AddSiteButton" Content="Add Site" HorizontalAlignment="Right"
Margin="10,0,0,0" VerticalAlignment="Top" Click="AddSiteButton_Click"/>
</StackPanel>
StackPanel control arranges child elements into a single line that can be oriented horizontally or vertically. When the Orientation property is set to Vertical(The default value is Vertical), the VerticalAlignment property of the button control will be invalid. Similarly, when the Orientation property is set to Horizontal, the HorizontalAlignment property of the button control will be invalid.
If you add a button control into a StackPanel, the HorizontalAlignment property and VerticalAlignment property of the button control will not work at the same time, that is, the button control can not be centered in a StackPanel.
We suggest that you could add the button control to a Grid panel, like this:
Grid gridPanel1 = new Grid();
Button TestButton = new Button();
TestButton.Content = "Test";
TestButton.HorizontalAlignment = HorizontalAlignment.Center;
TestButton.VerticalAlignment = VerticalAlignment.Center;
gridPanel1.Children.Add(TestButton);
Window.Current.Content = gridPanel1;

Fixed positioning in XAML

I have a Windows Store-style WPF application, and I just added search to it. When I click the Search button in the app bar, I set my FlyoutPresenter containing the SearchBox to Visible. This button is placed in the lower right-hand corner. It works good on computers with keyboards, but I ran into a problem when the virtual keyboard, or InputPane, opens. First, the keyboard covered the box. I solved that problem by checking and adjusting the margin of the box when the box is in focus, but when I scroll the page to the very top and bottom, the control starts moving on the page. Here is my minimal code:
XAML:
<Grid Background="White" x:Name="MainGrid">
<!-- App Bar with Search button -->
<AppBar x:Name="BAppBar" VerticalAlignment="Bottom">
<CommandBar>
<CommandBar.PrimaryCommands>
<AppBarButton Icon="Find" Label="Search" Click="Search_Click"/>
</CommandBar.PrimaryCommands>
</CommandBar>
</AppBar>
<!-- Search button and Close button -->
<FlyoutPresenter VerticalAlignment="Top" Name="SearchPop" Visibility="Collapsed">
<StackPanel Orientation="Horizontal">
<SearchBox Name="Search" GotFocus="Search_Focus" LostFocus="Search_Focus"/>
<AppBarButton Name="SearchClose" Icon="Cancel" Click="Search_Close" />
</StackPanel>
</FlyoutPresenter>
</Grid>
C#:
public partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
// Close app bar, show search box, and set margin to bottom of page
private void Search_Click(object sender, RoutedEventArgs e)
{
BAppBar.IsOpen = false;
SearchPop.Visibility = Windows.UI.Xaml.Visibility.Visible;
SearchPop.Margin = new Thickness(0, MainGrid.ActualHeight - SearchPop.ActualHeight, 0, 0);
}
// Set margin for opening/closing virtual keyboard
private void Search_Focus(object sender, RoutedEventArgs e)
{
Windows.UI.ViewManagement.InputPane.GetForCurrentView().Showing += (s, args) =>
{
double flyoutOffset = (int)args.OccludedRect.Height - SearchPop.ActualHeight;
SearchPop.Margin = new Thickness(0, flyoutOffset, 0, 0);
};
Windows.UI.ViewManagement.InputPane.GetForCurrentView().Hiding += (s, args) =>
{
SearchPop.Margin = new Thickness(0, MainGrid.ActualHeight - SearchPop.ActualHeight, 0, 0);
};
}
// Close search
private void Search_Close(object sender, RoutedEventArgs e)
{
SearchPop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
What I need is for the box to not be affected by the user scrolling in the screen. In HTML, this is called Fixed Positioning. I have read that it is not natively possible in XAML, but that there are workarounds. I have read these MSDN and SO links, but they didn't really help:
http://social.msdn.microsoft.com/Forums/en-US/9779328a-a7cd-447d-a4ac-bcc952083f43/fixed-positioning-in-wpf?forum=wpf
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/7349d01d-dc0e-4e1c-9327-df90e00fbebf/how-to-handle-the-appearance-of-the-onscreen-keyboard?forum=winappswithcsharp
Popup control moves with parent
You can simulate the fixed behavior in XAML in a very simple way:
<Grid Background="White" x:Name="MainGrid">
<ContentControl VerticalAligment="Stretch" HorizontalAligment="Stretch">
<!--All other visual controls, the float item will be located over all controls located here, even scrolls viewers-->
</ContentControl>
<!-- Float item -->
<SomeControl>
<!--The control you want be over in the fixed position,
you can set the layout to it, and locate it where you want
just set the Vertical/Horizontal Aligment, margin, height, width-->
</SomeControl>
</Grid>
(Sorry if code sample has some sintax errors, I had write it in the fly)
Also wpf has some controls that are displayed on a layer over all other, this elements are context menus, tooltips and adorners, you also could try them.
I hope this ideas helps.

windows phone 8 grid checkbox check and uncheck

i have a 100 * 100 grid on one of the page in my app. i have a single checkbox on the top right of the grid.
what i want is that when the user tap or click on the grid first time the checkbox become checked and when i again taps on the grid the checkbox becomes unchecked. how can i achieve it? i am talking about the metro type checkboxes here. or could i use checkbox itself in this manner? is grid the right way to go?
In short i need some guidelines in solving the above problem?
This may work for you
<Grid Height="100" Width="100" Background="Beige" Tap="Grid_Tap" >
</Grid>
<CheckBox x:Name="gridCheckBox" Content="CheckBox" HorizontalAlignment="Left" Margin="369,47,0,0" VerticalAlignment="Top"/>
then for making the checkbox checked and unchecked on the tap event of the grid we need to add the following code
private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (gridCheckBox.IsChecked == true)
{
gridCheckBox.IsChecked = false;
}
else
{
gridCheckBox.IsChecked = true;
}
}
gridcheckbox.IsChecked = (gridcheckbox.IsChecked == true) ? false : true;

Categories