I made a method that will allow me to lock the size of any Windows in my application. The method itself works perfectly, however when I pass in the fixed size of my XAML content, it doesn't render properly. As you can see from the XAML, the canvas size is locked at 725x305. However, when I pass those values into my method, the AppWindow cuts off a portion of the picture. I have to set the AppWindow closer to 925x425 to get it to show the whole background image. Is anyone able to explain to me what the difference between the XAML & AppWindow height and width? Is it possible to calculate the exact AppWindow size needed based on the content size?
What I expect the window to look like:
What it actually looks like:
<Window
x:Class="Aerloc_App.Views.LoginWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Aerloc_App.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Canvas Width="725" Height="305">
<Canvas.Background>
<ImageBrush ImageSource="../Assets/Aerloc_Logo.png"
Opacity=".75"
Stretch="Uniform"/>
</Canvas.Background>
<StackPanel Canvas.Left="400" Canvas.Top="25">
<!-- Username & Password Box -->
<TextBox PlaceholderText="Username"
Text="{x:Bind Path=ViewModel.Username, Mode=TwoWay}"
Width="300"
Opacity="1"/>
<PasswordBox PlaceholderText="Password"
PasswordChanged="{x:Bind Path=ViewModel.PasswordBox_PasswordChanged}"
KeyDown="{x:Bind Path=ViewModel.PasswordBox_KeyDown}"
Width="300"
Margin="0,8,0,8"
Opacity="1"/>
<!-- Error Notification Window -->
<TextBlock Text="{x:Bind Path=ViewModel.ErrorMessage, Mode=OneWay}"
Foreground="GhostWhite"
FontWeight="ExtraBold"
Width="300"
TextAlignment="Right"/>
</StackPanel>
</Canvas>
public void SetWindowSize(Window window, int width, int height, bool isResizable = true)
{
IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
var presenter = appWindow.Presenter as OverlappedPresenter;
appWindow.Resize(new Windows.Graphics.SizeInt32 { Width = width, Height = height });
presenter.IsResizable = isResizable;
presenter.IsMaximizable = isResizable;
}
Related
I have a Pivot in a Grid with 3 tabs, but the URL as source is not showing up when I run the application for 2 of my WebViews (the 3rd has not yet been configured). When I take the WebView out of my Pivot and put it in the Grid only, it shows fine.
My xaml file:
<Page
x:Class="Study_Bot.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Study_Bot"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="1270">
<Pivot x:Name="rootPivot" Title="" Margin="0,312,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" Height="388" Width="1138">
<Pivot.RightHeader>
<CommandBar ClosedDisplayMode="Compact">
<AppBarButton Icon="Back" Label="Previous" Click="BackButton_Click"/>
<AppBarButton Icon="Forward" Label="Next" Click="NextButton_Click"/>
</CommandBar>
</Pivot.RightHeader>
<PivotItem Header="Encyclopedia">
<!--Pivot content goes here-->
<WebView x:Name="encyclopedia" Source="https://www.britannica.com/search?query=virus" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</PivotItem>
<PivotItem Header="Journals">
<!--Pivot content goes here-->
<WebView x:Name="journals" Source="http://search.sciencemag.org/?searchTerm=virus&order=tfidf&limit=textFields&pageSize=10&&" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</PivotItem>
<PivotItem Header="News / Blogs">
<!--Pivot content goes here-->
<WebView x:Name="newsBlogs" />
</PivotItem>
</Pivot>
</Grid>
</Page>
My xaml.cs file:
namespace Study_Bot
{
/// <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();
}
private void BackButton_Click(object sender, RoutedEventArgs e)
{
if (rootPivot.SelectedIndex > 0)
{
// If not at the first item, go back to the previous one.
rootPivot.SelectedIndex -= 1;
}
else
{
// The first PivotItem is selected, so loop around to the last item.
rootPivot.SelectedIndex = rootPivot.Items.Count - 1;
}
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
if (rootPivot.SelectedIndex < rootPivot.Items.Count - 1)
{
// If not at the last item, go to the next one.
rootPivot.SelectedIndex += 1;
}
else
{
// The last PivotItem is selected, so loop around to the first item.
rootPivot.SelectedIndex = 0;
}
}
}
}
I am not understanding when you fix the height and width of your pivot, so why you align it center or top because it already capture grid according to margin, and if you are not stretch its vertical and horizontal alignment within the grid, this will take space only upto defined for internal elements and webview height width is not fixed so.
<Pivot x:Name="rootPivot" Title="" Margin="0,312,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="388" Width="1138">
that's all or alternately remove horizontal and vertical alignment.
*Note: in your app the way you put margin, height and width this will cause problems relating to screen size and adaptiveness in short your app elements will not adjust or resize according to screen size e.g PC,Tablet or Mobile
I want to make the window have the effect can change the whole window which has many elements evenly to white, as the window behind in the picture:
I use code like
public MainWindow()
{
this.Opacity = 0.5;
}
but it change to black
How to make it whole evenly change to white even when there're many Element in the Window and don't set the window Style to none?(Because set Window AllowTransparent seems have to set the Style to none at the same time)
I hope can using code to do it, because I want to do it dynamically.
(Or possibly it use UserControl but not Window to achieve this effect? maybe the UserControl use with the Window and set the UserControl to Transparent can do it
----After I try, I find UserControl doesn't have property AllowTransparent, so it seems imposible use this way )
Basically, you have two options:
Use white Background color on Window and change Opacity on the window children, so the white starts to shine through
<Window Background="White">
<Grid Opacity="{Binding WhiteOutVisibility}" Background="WhiteSmoke">
<YourContent/>
</Grid>
</Window>
Use a white overlay control with alpha or Opacity that lets the actual content shine through
<Grid>
<YourContent/>
<Border Background="#80ffffff" Visibility="{Binding WhiteOutVisibility}"/>
</Grid>
In my opinion, you should use a white overlay if you want to block user interaction with the window content and white background if you want to continue user interaction.
If you need to fade only the client area, you can just put overlay - some empty semitransparent control over all the content on the window.
You can achieve this effect by laying a canvas over your window, and setting the background to white and an opacity value. Some xaml like this will work. Just change the UserControl for Window.
<UserControl x:Class="View.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="40" d:DesignWidth="100">
<Grid>
<TextBox Text="Hello there" />
<!-- this will show faintly -->
<Canvas Background="White" Opacity="0.8"></Canvas>
</Grid>
</UserControl>
This xaml looks like this:
The Window type has property AllowsTransparency. You can find it property on your window properties in MSVisualStudio. This can solve your problem.
Thanks for Phillip Ngan and grek40 s' answer,
both Grid and Canvas with background white and opacity works,
I write some test code that can show the effect
Xaml Part
<Window x:Class="WPFAbitraryTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Grid.Row="0" Background="Blue" Foreground="White" FontSize="20" Click="SwitchOpacity_OnClick">Clcik to SwitchOpacity</Button>
<Button Grid.Row="1" Background="ForestGreen">hi2</Button>
<ListBox Grid.Row="2" Background="Orange">
<ListBoxItem>ListBox Item #1</ListBoxItem>
<ListBoxItem>ListBox Item #2</ListBoxItem>
<ListBoxItem>ListBox Item #3</ListBoxItem>
</ListBox>
<!-- <Grid Grid.Row="1" Grid.RowSpan="2" Opacity="0.9" Background="WhiteSmoke"/> -->
<Canvas Name="WhiteMaskCanvas" Grid.Row="1" Grid.RowSpan="2" Background="White" Opacity="0.5"></Canvas>
</Grid>
</Window>
.
Class Part
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void SwitchOpacity_OnClick(object sender, RoutedEventArgs e)
{
int opacityVal = 0;
Task.Factory.StartNew(() =>
{
for (int i = 0; i <= 1000; i++)
{
int j = 0;
Thread.Sleep(100);
//Use ++ % to change Opacity
this.Dispatcher.Invoke(
DispatcherPriority.SystemIdle,
new Action(() =>
{
WhiteMaskCanvas.Opacity = ++opacityVal % 10 / 10.0;
}));
////Use Abs Cosine to Change Opacity
//this.Dispatcher.Invoke(
// DispatcherPriority.SystemIdle,
// new Action(() =>
// {
// WhiteMaskCanvas.Opacity =
// Math.Abs(Math.Sin(++opacityVal*0.1)) ;
// }));
}
});
}
}
.
The Result:
.
further code,
if want to make the canvas mask whole window, you can change the canvas to
<Canvas Name="WhiteMaskCanvas" Grid.Row="0" Grid.RowSpan="3" Background="White" Opacity="0.5"></Canvas>
and add code to class:
public MainWindow()
{
InitializeComponent();
WhiteMaskCanvas.Visibility = Visibility.Collapsed;
}
private void SwitchOpacity_OnClick(object sender, RoutedEventArgs e)
{
WhiteMaskCanvas.Visibility = Visibility.Visible;
int opacityVal = 0;
Task.Factory.StartNew(() =>
{
//below same as code above
I am working on a Windows Store app in which I have a user control as a data template inside flipview.
User Control: (ImagePage.xaml)
<UserControl
x:Name="userControl"
x:Class="MWC_online.Classes.ImagePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MWC_online.Classes"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768"
d:DesignWidth="1366">
<Grid Background="#FFF0F0F0" Margin="4,0">
...
<Image Source="{Binding Img}" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" />
<StackPanel x:Name="stackPanel" HorizontalAlignment="Left" Margin="984,83,0,0" Width="325">
<Grid Background="{Binding Colour}">
<TextBlock Margin="30,30,30,15" Text="{Binding TextContent1}" FontWeight="Light" TextWrapping="Wrap" Foreground="#FF00ABE8" FontSize="29" />
</Grid>
<Grid Background="{Binding Colour}">
<TextBlock Margin="30,10,30,30" Text="{Binding TextContent2}" TextWrapping="Wrap" Foreground="#FF606060" FontSize="17" />
</Grid>
</StackPanel>
</Grid>
</UserControl>
User Control Class: (ImagePage.xaml.cs)
private static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){
StackPanel stackPanel = (StackPanel)d;
stackPanel.Visibility = Visibility.Collapsed;
}
public string TextContent1
{
get { return (string)GetValue(TextContent1Property); }
set { SetValue(TextContent1Property, value); }
}
public static readonly DependencyProperty TextContent1Property =
DependencyProperty.Register("TextContent1", typeof(string), typeof(ImagePage), new PropertyMetadata("", new PropertyChangedCallback(OnTextContent1Changed)));
private static void OnTextContent1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// what I want to do is if TextContent1 or TextContent2 has no value
// turn the stackpanel visibility to collapsed
StackPanel stackPanel = (StackPanel)d;
stackPanel.Visibility = Visibility.Collapsed;
}
Everything is working fine EXCEPT the OnTextContent1Changed is not firing! so I dont know if this is the right way of doing things but basically I just want to switch an UI element within the user control ON or OFF depending on the data binding that is being fed into it.
The TextBlock doesn't have a DataContext to find the DependencyProperty on. If you give your Grid a name in ImagePage.xaml:
<Grid Background="#FFF0F0F0" Margin="4,0" x:Name="MyGrid">
Then you can set its DataContext in the ImagePage constructor in ImagePage.xaml.cs:
public ImagePage()
{
InitializeComponent();
MyGrid.DataContext = this;
}
Which tells the Grid (and its decendents) to look for Dependency Properties on the ImagePage class. With this, the Dependency Property should get bound correctly. Another problem, though, is that you're telling the DependencyProperty that it is on an ImagePage with typeof(ImagePage), but then casting it to a StackPanel, which will fail every time:
StackPanel stackPanel = (StackPanel)d; // Throws System.InvalidCastException
You could fix this by giving a name to the StackPanel and referencing it directly in your .cs file.
So, basically I filter touch inputs to only recognise Finger and Tag touches from every screen except for the Training Screen where I recognise Finger, Tag and Blob touches. I do this by overriding the OnPreviewTouchDown(TouchEventArgs e) method in MainWindow which is a SurfaceWindow. See code below for override method.
protected override void OnPreviewTouchDown(TouchEventArgs e)
{
bool isFinger = e.TouchDevice.GetIsFingerRecognized();
bool isTag = e.TouchDevice.GetIsTagRecognized();
//Allows all touches on Train Screen. Only fingers and tags everywhere else
if (e.Source.ToString() != "dtt_app.TrainScreen")
{
if (isFinger == false && isTag == false)
{
e.Handled = true;
return;
}
}
base.OnPreviewTouchDown(e);
}
This is what my Token Visualisation code looks like
for (int i = 1; i < 10; i++)
{
TagVisualizationDefinition TokenTagDef =
new TagVisualizationDefinition();
// The tag value that this definition will respond to.
TokenTagDef.Value = i;
// The .xaml file for the UI
TokenTagDef.Source =
new Uri("TokenVisualization.xaml", UriKind.Relative);
// The maximum number for this tag value.
TokenTagDef.MaxCount = 100;
// Orientation offset (default).
TokenTagDef.OrientationOffsetFromTag = 0.0;
// Physical offset (horizontal inches, vertical inches).
TokenTagDef.PhysicalCenterOffsetFromTag = new Vector(0.0, 0.0);
// Tag removal behavior (default).
TokenTagDef.TagRemovedBehavior = TagRemovedBehavior.Fade;
// Orient UI to tag? (default).
TokenTagDef.UsesTagOrientation = true;
// Add the definition to the collection.
MyTagVisualizer.Definitions.Add(TokenTagDef);
}
And this is the XAML code for the TrainScreen which is a UserControl that is set as the content of MainWindow
<UserControl x:Class="dtt_app.TrainScreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:s="http://schemas.microsoft.com/surface/2008"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<s:TagVisualizer
Name="MyTagVisualizer"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Background="Transparent"
Height="Auto" Width="Auto"
VisualizationAdded="OnVisualizationAdded">
<Canvas Name="canvas" Width="{Binding ElementName=topWindow, Path=ActualWidth}" Height="{Binding ElementName=topWindow, Path=ActualHeight}">
<Label Width ="500" Canvas.Top="100" Content="Label" Name="Instruction" FontSize="30" HorizontalContentAlignment="Center"/>
<Popup Name="Positive" Width="240" Height="200" Placement="MousePoint" AllowsTransparency="True" IsEnabled="True" IsOpen="False">
<Image Source="images/SmileyFace.png">
</Image>
</Popup>
<Popup Name="Negative" Width="240" Height="200" Placement="MousePoint" IsEnabled="True" AllowsTransparency="True" IsOpen="False">
<Image Source="images/SadFace.png">
</Image>
</Popup>
</Canvas>
</s:TagVisualizer>
</Grid>
</UserControl>
I have no idea why any touch input is just not recognised whenever a tagged object is on the table. Any help with this would be greatly appreciated. Please. I've exhausted every possibility, and I really need to figure this out since time is running out. Thanks in advance.
Most likely the problem is that input is hit testing to your tagvisualization (you didnt show us the code for that). Remember that "Transparent" is hit tested (use Background=null or IsHitTestVisible=false to make something not hit test)
You can confirm it's not a hardware/platform problem by running the Input Visualizer tool.
When I set my image margin in run-time it acts strange, different then when I set it via xaml code.
I want the margin value to be (40, 16, 0, 0).
When I add it in run-time, my code is this:
System.Windows.Controls.Image proba = new System.Windows.Controls.Image();
ImageSource imageSource = GetSlidePart(PresentationDocument.Open(path, false), 0, "rId2");
proba.Source = imageSource;
proba.Width = 2245721 / 9525;
proba.Height = 2286004 / 9525;
proba.Margin = new Thickness(40, 16, 0, 0);
gridName.Children.Add(proba);
But, when I add image in xaml, the code in cs is this:
image1.Source = GetSlidePart(PresentationDocument.Open(path, false), 0, "rId2");
and the code in xaml is this:
<Window x:Class="GetInfoFromPptxFile.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="720" Width="960">
<Grid Name="gridName">
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="416,20,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<Image Height="150" HorizontalAlignment="Left" Margin="40,16,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
</Grid>
</Window>
When I run my program, image1 is exactly where I want it to be, and the image named proba is not. Why is this when I give them the same margin values?
That's because you're not setting the horizontal and vertical alignments in C#.
Try adding:
proba.VerticalAlignment = VerticalAlignment.Top;
proba.HorizontalAlignment = HorizontalAlignment.Left;
and it'll look the same.