WebView not showing in Pivot, C# UWP - c#

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

Related

Can i add elements programatically to XAML? WPF c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I want to add canvas elements by user input. Something like when a button is clicked, a new <Ellipse/> element is added to the XAML file, inside the Canvas.
<Canvas x:Name="GraphDisplayFrame" Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="3" Grid.RowSpan="4">
<Ellipse
Width="50"
Height="50"
Stroke="Black"
StrokeThickness="2"
Canvas.Left="100"
Canvas.Top="100" />
</Canvas>
I'm new to WPF, i'm not sure if this is the right way to do this.
The other thing i'm trying is System.Windows.Media but manipulating the XAMl file looks easier and nicer, since then the locations of the drawings are anchored to the canvas. I'm not sure if i can achieve something similar with System.Windows.Media.
So my question is in the title, but I'm open to other suggestions.
You probably want to learn about Bindings in WPF. Let's say you want your Ellipses be added by user's input (e.g. on Button click) to your Canvas. I'm not sure about Canvas usage for that purpose (it hasn't auto-alignments for child elements), so I used WrapPanel instead (to allow it align items). And we need 2 Buttons (to Add and Remove Ellipses). And I add a Label to display current amount of Ellipses that we have.
XAML:
<Window x:Class="WpfApp2.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:WpfApp2"
mc:Ignorable="d"
Name ="mainWindow"
Title="Main Window"
Width="800"
MaxWidth="800"
Height="450"
MaxHeight="450">
<Grid x:Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="50*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
</Grid.RowDefinitions>
<Label Content="{Binding ElementName=mainWindow, Path=EllipsesCount, UpdateSourceTrigger=PropertyChanged}"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Grid.Row="0"
Background="DimGray"
Foreground="White"
Margin="15,35" />
<Button x:Name="BtnAddEllipse"
Content="ADD ELLIPSE"
Grid.Row="1"
Margin="10, 25" FontSize="22" FontWeight="Bold"
Background="LightGreen"/>
<Button x:Name="BtnRemoveEllipse"
Content="REMOVE ELLIPSE"
Grid.Row="2"
Margin="10, 25" FontSize="22" FontWeight="Bold"
Background="IndianRed"/>
<WrapPanel Orientation="Horizontal"
Background="Gainsboro"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Grid.Column="1"
Grid.Row="0"
Grid.ColumnSpan="3"
Grid.RowSpan="4" >
<ItemsControl ItemsSource="{Binding ElementName=mainWindow, Path=Ellipses, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</WrapPanel>
</Grid>
</Window>
Here you see that Label.Content property is binded to some EllipsesCount property (you'll see it in code-behind below). Also as WrapPanel is binded to Ellipses property.
Code-behind: (for copypaste purpose)
using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfApp2
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
// Text for Label about Ellipses amount in collection
private object _ellipsesCount = "Current ellipses count: 0";
public object EllipsesCount
{
get => _ellipsesCount;
set
{
_ellipsesCount = "Current ellipses count: " + value;
// When we set new value to this property -
// we call OnPropertyChanged notifier, so Label
// would be "informed" about this change and will get new value
OnPropertyChanged(nameof(EllipsesCount));
}
}
// Collection for Ellipses
private ObservableCollection<Ellipse> _ellipses;
public ObservableCollection<Ellipse> Ellipses
{
get => _ellipses;
set
{
_ellipses = value;
OnPropertyChanged(nameof(Ellipses));
}
}
// Hanlder, which would notify our Controls about property changes, so they will "update" itself with new values
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
// Just for random colors
private readonly Random random = new Random();
public MainWindow()
{
InitializeComponent();
// Initialize collection of Ellipses
Ellipses = new ObservableCollection<Ellipse>();
// Handle when collection is changed to update Label
// with a new amount of Ellipses
Ellipses.CollectionChanged += delegate
{
// Update counter of ellipses when new one added or existing removed
EllipsesCount = Ellipses.Count;
};
BtnAddEllipse.Click += delegate
{
// Create an Ellipse with random stroke color
var ellipse = new Ellipse
{
Width = 50,
Height = 50,
Margin = new Thickness(3),
Stroke = new SolidColorBrush(Color.FromRgb((byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255))),
StrokeThickness = 3
};
// Add to collection of ellipses
Ellipses.Add(ellipse);
};
BtnRemoveEllipse.Click += delegate
{
// Check, that Ellipses collection isn't null and empty,
// so we can remove something from it
if (Ellipses?.Count > 0)
Ellipses.Remove(Ellipses.Last()); // Removing last element
};
}
}
}
So at result you see, actually, "content of collection of Ellipses", without adding Ellipses directly to window. Binding makes WrapPanel to use collection of Ellipses as source of child elements, that should be in that WrapPanel (instead of original my answer, where we add Ellipse to Canvas as Children).
ORIGINAL answer.
Yes, you can. For example (based on your XAML):
XAML (empty window):
<Window x:Class="WPFApp.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:WPFApp"
mc:Ignorable="d">
<!-- No even Grid here -->
</Window>
Code-behind (check comments also):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Setting Window properties (they not exists in XAML)
// XAML: <Window ... Title="Main Window" Height="450" Width="800">...
this.Title = "Main Window";
this.Height = 450;
this.Width = 800;
// Create main Grid and register some its name
// XAML: ...
var mainGrid = new System.Windows.Controls.Grid();
this.RegisterName("MainGrid", mainGrid);
// Add row and column definitions (as Canvas below needs, at least 4 rows and 3 columns)
for (int i = 0; i < 4; i++)
{
mainGrid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition { Height = new GridLength(50, GridUnitType.Star) });
if (i < 3) // Needn't 4th column
mainGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = new GridLength(50, GridUnitType.Star) });
}
// Create Canvas and register its name too
// XAML: ...
var canvas = new System.Windows.Controls.Canvas
{
// Just to be able see it at Window
Background = System.Windows.Media.Brushes.LightGray
};
this.RegisterName("GraphDisplayFrame", canvas);
canvas.SetValue(System.Windows.Controls.Grid.ColumnProperty, 1);
canvas.SetValue(System.Windows.Controls.Grid.RowProperty, 0);
canvas.SetValue(System.Windows.Controls.Grid.ColumnSpanProperty, 3);
canvas.SetValue(System.Windows.Controls.Grid.RowSpanProperty, 4);
// Create Ellipse (child canvas element)
// XAML: ...
var ellipse = new System.Windows.Shapes.Ellipse
{
Width = 50,
Height = 50,
Stroke = System.Windows.Media.Brushes.Black,
StrokeThickness = 2
};
ellipse.SetValue(System.Windows.Controls.Canvas.LeftProperty, 100D);
ellipse.SetValue(System.Windows.Controls.Canvas.TopProperty, 100D);
// Add child Ellipse to Canvas
canvas.Children.Add(ellipse);
// or you already can find Canvas by its name:
(this.FindName("GraphDisplayFrame") as System.Windows.Controls.Canvas).Children.Add(ellipse);
// Add Canvas to MainGrid. Find Grid by its registered name too
(this.FindName("MainGrid") as System.Windows.Controls.Grid).Children.Add(canvas);
// Set main Grid as window content
this.Content = mainGrid;
}
}
So, as you can see, XAML markuping is quite more compact, that code-behinded one.

WPF - How to make Window opacity to white

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

Finger and Blob Touch Inputs not recognised when Tagged Object is on Samsung SUR40 table

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.

Window SizeToContent and ListBox sizing

I am trying to figure out how to use a WPF list box in conjunction with a window that has its SizeToContent property set to WidthAndHeight. The MainWindow has a grid with two rows and two columns. In the bottom right quadrant, I have a list box. I want the rest of the controls in the window to control the size of the window, and the list box to simply fill the available space. Currently, the list box is expanding to fit its contents, which causes the entire MainWindow to expand.
Note: I attempted to create a simple example, but want to point out that in my real scenario I'm using MVVM, and the controls that I want to determine the window width/height are bound to properties in a viewmodel that have their values set after the window is loaded.
Edit to add: The list box is bound to its content before the controls that I want to determine size are, and I don't have control over that.
Here is what the MainWindow currently looks like at startup:
Notice the red and blue bars which indicate what I'm not wanting to happen. Content in that area should only be visible by scroll bars.
Here is what I want the MainWindow to look like at startup:
Notice the size of the MainWindow is determined by the text blocks along the top and left sides, and the list box fills the available space and uses scrollbars if necessary.
Here is some sample code...
MainWindow.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" SizeToContent="WidthAndHeight">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="The window should fit to the width of this" FontSize="15"/>
<Canvas Background="Red" Grid.Column="1"/>
</Grid>
<Grid Grid.Row="1" Grid.RowSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="The window should fit to the height of this" FontSize="15">
<TextBlock.LayoutTransform>
<RotateTransform Angle="-90"/>
</TextBlock.LayoutTransform>
</TextBlock>
<Canvas Background="Blue" Grid.Row="1"/>
</Grid>
<Grid Grid.Row="2" Grid.Column="1">
<ListBox Name="ListBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var Messages = new ObservableCollection<string>() { "This is a long string to demonstrate that the list box content is determining window width" };
for (int i = 0; i < 16; i++)
Messages.Add("Test" + i);
for (int i = 0; i < 4; i++)
Messages.Add("this text should be visible by vertical scrollbars only");
ListBox1.ItemsSource = Messages;
}
}
Set the list box ItemsSource, and set SizeToContent=Manual after the Window has loaded.
public MainWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
SizeToContent = SizeToContent.Manual;
var messages = new ObservableCollection<string>
{
"This is a long string to demonstrate that the list" +
" box content is determining window width"
};
for (int i = 0; i < 16; i++)
{
messages.Add("Test" + i);
}
for (int i = 0; i < 4; i++)
{
messages.Add("this text should be visible by vertical scrollbars only");
}
ListBox1.ItemsSource = messages;
}
In this way the main window is initially sized to fit the content (with no data in the listbox), and then the listbox displays its items with scrollbars.

want to trigger an event when the user touch the left part of the display

I have used the scrollviewer in my app to show images. i need to move the stackpanel inside the scrollviewer right side when the user touches the right side of the display,and to move on left when user touches the left side. I tries in XNA framework but vector2 class does not check the postion of finger. How to achieve this.
You should be able to hook into the MouseLeftButtonDown event of the page. And then calculate where the user touched the screen with the MouseEventArgs.GetPosition Method. Here's a basic example to demonstrate this concept:
XAML
<ScrollViewer Background="Red">
<StackPanel x:Name="MyStackPanel"
Orientation="Vertical"
Width="150"
Background="Black"
HorizontalAlignment="Left">
<ItemsControl ItemsSource="{Binding Images}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Width="48" Height="48" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</ScrollViewer>
Code Behind
public MainPage()
{
InitializeComponent();
this.MouseLeftButtonDown += OnMouseDown;
}
private void OnMouseDown( object sender, MouseButtonEventArgs e )
{
Point pos = e.GetPosition( this );
double half = this.ActualWidth / 2;
if( pos.X < half )
{
MyStackPanel.HorizontalAlignment = HorizontalAlignment.Right;
}
else
{
MyStackPanel.HorizontalAlignment = HorizontalAlignment.Left;
}
}

Categories

Resources