WPF controls do not align - c#

NOTE: This is one of the first time I'm using WPF.
I am trying to align a certain control, let's say a button for now, in the bottom right corner. But when I debug my application, it misses 8 pixels to the bottom and right. I will attach 2 pictures to show you what happens.
How do I keep the button in place?
My XAML code:
<Window x:Class="Plugin_Manager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Plugin Manager" Height="350" Width="525" Loaded="Window_Loaded_1">
<Grid x:Name="GridMain">
<Button Content="Refresh" Margin="432,288,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="75"/>
<ListView HorizontalAlignment="Left" Height="273" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">
<ListView.View>
<GridView>
<GridViewColumn/>
</GridView>
</ListView.View>
</ListView>
</Grid>

If you choose to use Grid layout you should try to avoid placing objects via Margin. Margin should be used to create buffer around an object, not move it to a specific point in the window. Use the layout manager's power to your advantage!
Here is a Grid example that does what you are looking for.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListView Grid.Row="0" />
<Button Grid.Row="1" HorizontalAlignment="Right" Content="Push Me" />
</Grid>
I would also read up on Layout Manager in WPF. There are several; each having its own advantages & disadvantages.
Here is a DockPanel version.
<DockPanel>
<Button DockPanel.Dock="Bottom" HorizontalAlignment="Right" Content="Push Me" />
<ListView />
</DockPanel>
To create your buffer between the button and the window chrome you could do a few different things:
<Grid Margin="10"> will apply a 10 pixel space between all content and the window chrome on all side.
<Grid Margin="0,0,10,10"> would indent all content, but only on the right & bottom.
<Grid Margin="10,0,10,10"> indents all around, except the top (I commonly do this one, with a different margin value).
<Button Margin="0,0,10,10"> would indent only the button from the chrome (this is the direct answer to your comment question).
Replace the Grid above with DockPanel for the second example, or whatever other Layout Manager you are using.
A usability side note: Your confirmation buttons (I'm assuming your button will be an Ok/Cancel type button) should not be indented differently from the rest of your content. All controls that butt up against the right margin should do so at the same point (i.e., you can draw a vertical line down the right side of them all).
So, using your question's example: your button should not be indented 10 pixels to the right while your list box is not. Keeping things lined up will improve the overall look to your application.
(this ends my "usability and look-and-feel is important" side note) :)

<Button VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="5"/>

Some code example will help. Try using the alignment in xaml for your button as shown below. Ensure that the margins on the button are 0.
<Button Margin="0" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
Looking at the sample code, it is your margins and the alignment you have that are probably causing that.
Just some pointers that may help. Instead of using large margins to align the controls, I find it much easier to work with Column and Row definitions on the grid. This way you can align your controls using the grid and they will size properly as you resize your window. I attached an example in hopes it helps in your new adventures with WPF!
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="Version Date" Margin="3" VerticalAlignment="Center"/>
<TextBlock Grid.Column="0" Grid.Row="1" Text="{Binding DateSubmitted}" Margin="3"/>
<TextBlock Grid.Column="1" Grid.Row="0" Text="Report" Margin="3" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding ReportName}" Margin="3"/>
</Grid>

Related

UWP AutoCompleteBox in ContentDialog not sizing correctly - text area larger than drawn

I have an AutoCompleteTextBox in UWP is exhibiting a really odd behavior, and I can't figure out what's causing it. The TextBox is in a Grid, but the user can type past the bounds of the TextBox, so the first and last characters of each line are hidden behind the surrounding border. I've taken some screenshots to hopefully make this make more sense, as it's difficult to describe.
I've tried everything I can think of, but can't seem to get it to stop doing this. The only effect I had at all was in changing the HorizontalAlignment of the TextBox. Originally it was Stretch, and only the right side of the TextBox had cutoff letters. When I changed it to Center, it divided the cut-off section between both the left and right.
Does anybody have any ideas as to what's going on?
In the 1st picture, the actual TextBox area is defined by the box on the far outer edges of the ContentDialog [with the drag handles left of the (116)].
TextBox in VS Designer
In the second picture, the letters typed in the TextBox are 2 W's. If you look closely, you can just see the very right of the 1st W to the left of the full W there.
TextBox during execution
XAML:
<ContentDialog
x:Class="FlipPanelTest2.ComposeTweet"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:FlipPanelTest2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
RequestedTheme="Dark"
Title="{Binding SendTo}"
Foreground="Gray"
Width="600"
PrimaryButtonText="Cancel"
SecondaryButtonText="Tweet!"
SecondaryButtonStyle="{StaticResource TweetContentDialogButtonStyle}"
PrimaryButtonStyle="{StaticResource CancelButtonStyle}"
PrimaryButtonClick="ContentDialog_PrimaryButtonClick"
SecondaryButtonClick="ContentDialog_SecondaryButtonClick">
<Grid Width="Auto">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox x:Name="tweetText" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="White" TextWrapping="Wrap" Margin="2" TextChanged="TextBox_TextChanged" MaxHeight="180" MinHeight="112" Width="540" />
<StackPanel x:Name="characterCount" Orientation="Horizontal" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center">
<TextBlock x:Name="currentChars" HorizontalAlignment="Right" Grid.Row="1" FontSize="10" Text="{Binding TweetCharacters}" />
<TextBlock x:Name="charsDivider" HorizontalAlignment="Right" Grid.Row="1" FontSize="10" Text="/" />
<TextBlock x:Name="maxChars" HorizontalAlignment="Right" Grid.Row="1" FontSize="10" Text="{Binding MaxCharacters}" />
</StackPanel>
</Grid>
Well some more searching found the answer apparently. I hadn't thought to search for a max size on the ContentDialog, hence the reason I didn't find this before. Providing a link to the answer though for future people to use:
Quoted from ContentDialog max width:
In your App.xaml, try setting the ContentDialogMaxWidth to say, 800.
The default is 548. You might want to increase the height too.
<Application.Resources>
<x:Double x:Key="ContentDialogMaxWidth">800</x:Double>
<x:Double x:Key="ContentDialogMaxHeight">756</x:Double>
</Application.Resources>
ContentDialog max width
It's the last answer listed there, for some reason not the accepted answer. :)

How to automatically constraint rows/columns minimal size when using proportional grid sizing (*)?

Assuming we have a simple window:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Width="300" Height="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Margin="2,2,2,2">
<TextBlock
Text="Button 1.
It has some text.
Button shouldn't shrink less then the text size."
TextWrapping="WrapWithOverflow" />
</Button>
<Button Grid.Row="1" Content="Button 2" Margin="2,2,2,2" />
</Grid>
</Window>
Seems ok. However, after resizing, the upper button's content is cropped:
The desired layout should look like this:
In text: make the row height behave as proportional (*) with MinHeight equal to it's Auto height. In other words, have the Height to be Max(1*,Auto).
I assume that if WPF is capable of determining size of row automatically when set to Auto, then there should be a way to make it respect that size when proportionally sizing.
I found somewhat related questions (1, 2) but was unable to adapt techniques used there to my case.
The only result achieved at the moment is
Bind Button.MinHeight to nested TextBlock.ActualHeight
In code behind: enumerate all grid's childs placed in the first row, find maximal MinHeight, set it as RowDefinition.MinHeight. Looks crappy because the button is bigger then the text block.
May be something related to Measure & Arrange is needed? Or it is not worth the effort and it would be better to just place MinHeight manually (and also have some problems with the localization strings lenght differences)?
Here's a quick and easy trick.
Duplicate the control (and hide it) and use its measurements to find the MinHeight:
<Grid>
<Grid x:Name="dummyControl" VerticalAlignment="Center">
<Button Grid.Row="0" Margin="2,2,2,2" Visibility="Hidden" IsHitTestVisible="False">
<TextBlock
Text="Button 1.
It has some text.
Button shouldn't shrink less then the text size."
TextWrapping="WrapWithOverflow" />
</Button>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition MinHeight="{Binding ElementName=dummyControl, Path=ActualHeight}" Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Margin="2,2,2,2">
<TextBlock
Text="Button 1.
It has some text.
Button shouldn't shrink less then the text size."
TextWrapping="WrapWithOverflow" />
</Button>
<Button Grid.Row="1" Content="Button 2" Margin="2,2,2,2" />
</Grid>
</Grid>
VerticalAlignment of dummyControl should be anything other than Stretch

XAML element fill all remaining space

I have a WPF application and I'm trying to get the elements positioned correctly. There are just four elements, so it should be pretty straight-forward, but I just can't get it working.
One wrinkle is that the window resizes itself to (about) the size of the desktop window when it appears, so it doesn't have a fixed size.
The elements are supposed to be stacked from top to bottom, so a Stack Panel seemed natural. But The third element has to take up all the remaining space that the top two and bottom ones don't. No matter what I tried, it either took up too much space, or too little. I could only seem to get it working if I gave it a concrete pixel size which, as explained above, won't work.
The latest thing I've tried is a Dock Panel. While it looks correct in the Visual Studio designer, when executed, the third element--a Canvas--completely covers the bottom element.
My XAML:
<DockPanel>
<Button x:Name="btnClose" DockPanel.Dock="Top" Content="X"
HorizontalAlignment="Right" Margin="0,5,5,0" VerticalAlignment="Top"
Width="Auto" Height="Auto" Background="Black"
Foreground="White" Click="btnClose_Click"/>
<Label x:Name="lblTitle" DockPanel.Dock="Top" Content="My Title"
HorizontalAlignment="Center" VerticalAlignment="Top" Width="Auto"
Foreground="White" FontWeight="Bold" FontSize="22"/>
<Label x:Name="lblControls" DockPanel.Dock="Bottom" Content="Placeholder"
HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="Auto"
Height="Auto" Foreground="White" FontWeight="Bold" FontSize="22"/>
<Border x:Name="CanvasBorder" BorderBrush="White" BorderThickness="5" >
<Canvas x:Name="cvsChart" Grid.Row="0" HorizontalAlignment="Stretch"
VerticalAlignment="Top" Width="Auto">
</Canvas>
</Border>
</DockPanel>
Any idea about how to get that Canvas to stretch and fill all the space the other three don't take?
UPDATE
Since #Peter Duniho pretty much proved to me that the code worked, I tried an experiment and removed the resizing code I have in place for when the window appears. Taking it out, the window appears absolutely correctly. This is what I do to resize it to (mostly) the desktop size:
public const int WINDOW_OFFSET = 10;
...
int screenWidth = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
int screenHeight = (int)System.Windows.SystemParameters.PrimaryScreenHeight;
// center this window in desktop
Width = screenWidth - WINDOW_OFFSET;
Height = screenHeight - WINDOW_OFFSET;
Left = WINDOW_OFFSET/2;
Top = WINDOW_OFFSET/2;
So I did some poking around, and found a comment here on the 'Stack that said to get the WorkArea instead of the PrimaryScreenHeight. I tried that and voila!, the whole application window appears.
int screenWidth = (int)System.Windows.SystemParameters.WorkArea.Width;
int screenHeight = (int)System.Windows.SystemParameters.WorkArea.Height;
As it turns out, the bottom row was displaying, I just couldn't see it because it appeared below the bottom of the screen. Now I can see it, and I'm back to development heaven!
Thanks to everyone for their input!
There are a number of possible approaches to this. One of the most straightforward is to contain your elements in a Grid and set all but the third row height to Auto:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button x:Name="btnClose" Content="X" Grid.Row="0"
HorizontalAlignment="Right" Margin="0,5,5,0" VerticalAlignment="Top"
Width="Auto" Height="Auto" Background="Black"
Foreground="White" Click="btnClose_Click"/>
<Label x:Name="lblTitle" Content="My Title" Grid.Row="1"
HorizontalAlignment="Center" VerticalAlignment="Top" Width="Auto"
Foreground="White" FontWeight="Bold" FontSize="22"/>
<Label x:Name="lblControls" Content="Placeholder" Grid.Row="3"
HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="Auto"
Height="Auto" Foreground="White" FontWeight="Bold" FontSize="22"/>
<Border x:Name="CanvasBorder" BorderBrush="White" BorderThickness="5" Grid.Row="2">
<Canvas x:Name="cvsChart" Grid.Row="0" HorizontalAlignment="Stretch"
VerticalAlignment="Top" Width="Auto">
</Canvas>
</Border>
</Grid>
The default setting for a grid's row definition height is "*", which says to distribute all of the remaining space among all the rows with that setting. With only one row using that setting, it gets all of the leftover space.
This produces a window that looks like this:
(I set the window background to Gray so that your white text and border would be visible.)
Another option would in fact be to use DockPanel. It appears to me that the main problem in your attempt is that you set the lblControls element to DockPanel.Dock="Bottom" when it should be Top instead. When I change it to Top, it seems to work fine for me.
Based on your comment below, it seems you actually did want lblControls to be set to DockPanel.Dock="Bottom", and in fact the code you posted seems to also do what you want. It's not clear to me what is different from what the code you posted does and what you want it to do. It would be better if you would provide a good Minimal, Complete, and Verifiable code example that reliably reproduces the problem.
Remove the vertical alignment of the Canvas

WPF How do I make a Border width expand to fill available space in a DockPanel

I have a custom control ButtonRow which will end up going into a different control.
It is very simple, it has one Border, on label and one button.
I need to make it so that the border will extend its width to fill up to where the button is.
This is not happening as you can see in the below image:
The XAML can be found below. I have tried fiddling about with the horizontal alignment of both he label and the border, but they will only ever re-size to fit the text content of the label.
I know there are existing question with very similar problems and names, but none have needed to do quite the same thing or have helped me solve my problem.
I have tried using a StackPanel in horizontal alignment but all it did was make the button go next to the border.
How can I make the border expand to fill the available space?
<Grid>
<DockPanel Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="dockPanel1" VerticalAlignment="Top" Width="Auto">
<Border BorderBrush="#FFDADFE1" Background="#FFECF0F1" BorderThickness="1" Height="20" Name="bdrFilter" HorizontalAlignment="Stretch">
<Label Content="Filter..." FontStyle="Italic" Foreground="#FF6C7A89" Height="20" Name="lblFilter" Padding="5,0" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" />
</Border>
<Button Style="{StaticResource FlatButtonStyle}" Content="+" Height="20" HorizontalAlignment="Right" Name="btnAddFilter" VerticalAlignment="Top" Width="20" Foreground="#FF6C7A89" ForceCursor="True" BorderBrush="{x:Null}" />
</DockPanel>
</Grid>
(The button style does not affect its alignment or any other relevant properties)
A DockPanel is not the correct Panel to use for this requirement... like a StackPanel, it does not resize its contents. Instead, just use a regular Grid (which also uses less resources than a DockPanel):
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Border BorderBrush="#FFDADFE1" Background="#FFECF0F1" BorderThickness="1"
Height="20" Name="bdrFilter" VerticalAlignment="Top">
<Label Content="Filter..." FontStyle="Italic" Foreground="#FF6C7A89"
Height="20" Name="lblFilter" Padding="5,0" />
</Border>
<Button Grid.Column="1" Content="+" Height="20" HorizontalAlignment="Right"
Name="btnAddFilter" VerticalAlignment="Top" Width="20" Foreground="#FF6C7A89"
ForceCursor="True" BorderBrush="{x:Null}" />
</Grid>
Please see the Panels Overview page on MSDN for more information about the different Panels in WPF.
This might help you out. Setting LastChildFill=True inside a DockPanel does exactly what the name suggests.

Textbox in popup doesn't get focus in WPF application

I'm building a window for a kiosk application that has an admin screen to connect to a wifi network. Actually, I'm porting an existing WinForms app that already does this, but doesn't give us the flexibility we want to create a more interesting UI. So, we're moving to WPF.
The window is pretty straightforward, it has a listview to show networks that it finds, and if you click on one, it will connect to it. In order to connect, we need to prompt for the security code for that network if it needs one. To do this, we open a popup that has three sections - a "dialog-y" prompt section at the top, a spacer row, and a blank border that will sit behind an onscreen keyboard, but have nice rounded corners.
That top section has a header, a text box, and two buttons, connect and cancel. Again, nothing complex.
All this works. You click a network, we show the popup and the keyboard, except: the textbox for the passcode never gets the focus. Even if you click on it. No focus. The only trick I've found to get it to focus is to click off the popup (like back on the listview, which is already ignoring clicks if the popup is open, so it's safe), then click back on the textbox, and voila! focus. I really don't think I want to put that in a user manual though.
Here's the popup portion of the xaml:
<Popup x:Name="popPasscode" Placement="Top" HorizontalOffset="50" VerticalOffset="1000" AllowsTransparency="True" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="50" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="White" CornerRadius="20" Width="600" Height="400">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="#464646" Height="50" Margin="8,10,8,0" CornerRadius="25" >
<Label x:Name="lblTitleSecurityCode" Content="Enter the security code" Foreground="White" FontFamily="Arial" FontSize="30" FontWeight="Bold" HorizontalAlignment="Center"/>
</Border>
<TextBox Grid.Row="1" x:Name="tbPasscode" Height="50" FontFamily="Arial" FontSize="30" Margin="40,0,40,0"/>
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="10,0,10,10" HorizontalAlignment="Center">
<Controls:ImageButton x:Name="btnCodeConnect" Content="Connect" Height="70" Width="275" Foreground="Black" Style="{DynamicResource PlainButton}" FontFamily="Arial" FontSize="30" FontWeight="Bold" Click="btnCodeConnect_Click" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Controls:ImageButton x:Name="btnCodeCancel" Content="Cancel" Height="70" Width="275" Foreground="Black" Style="{DynamicResource PlainButton}" FontFamily="Arial" FontSize="30" FontWeight="Bold" Click="btnCodeCancel_Click" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</Grid>
</Border>
<Border Grid.Row="2" x:Name="brdrKbd" Background="White" CornerRadius="20" Width="1200" Height="420"/>
</Grid>
</Popup>
Here's what I'm currently trying to do during the listview click event to get focus to the control. Note that I tried to fake the "set focus to the listview, then set it to the textbox, but that didn't work.
// set the popup location and width and keyboard border width based on the current screen width
popPasscode.IsOpen = true;
// open the on-screen keyboard - synchronous call, doesn't return until it's open and idle
FocusManager.SetFocusedElement(this, lvAvailNetworks);
tbPasscode.Focusable = true;
FocusManager.SetFocusedElement(popPasscode, tbPasscode);
I've tried a couple different things for the DependencyElement for tbPasscode, but I really have no idea what I'm doing, or that what I'm doing is making any difference. Oh, did I mention I just finished my first week of WPF coding? Yup, WPF newbie alert.
I saw this post, but it didn't help much, since I thought I was already doing all that.
Instead of MouseDown, register to MouseUp event on ListView/ListViewItem.
In the handler you can do
popPasscode.IsOpen = true;
Keyboard.Focus(tbPasscode);
The MouseUp on your ListView takes focus away from the Popup, so open your Popup in MouseUp instead of MouseDown

Categories

Resources