How can I interact with a property in another frame? (C# / WPF) - c#

I'm currently learning C# and WPF. Therefore I'm programming a little music player. But now I came to a problem. I was implementing different frames for menu items and other things I display.
Then my problem occoured. I have a MediaElement in my MainWindow.XAML(.CS) and I have to interact with that Element also in my Player.XAML(.CS) - Which obviously controls it (the Player can pause, play, stop, etc the MediaElement). The other class CurrentPlaylist.XAML(.CS) displays the current Playlist in a Datagrid. It shows information and can interact with the MediaElement (Setting a new Song / Start to play the song).
I really have no idea on how to achieve it when I have different Frames.
Here's a little bit of Code.
MainWindow.XAML
<Grid>
<MediaElement Name="media" HorizontalAlignment="Left" Width="1" Height="1" LoadedBehavior="Manual" UnloadedBehavior="Stop"
MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded"/>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Frame Width="1280" Height="100" Grid.ColumnSpan="2" Grid.Row="1" VerticalAlignment="Bottom" Source="Player.xaml"></Frame>
<StackPanel HorizontalAlignment="Left" Width="50" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="2" Name="fullMenu" Background="{StaticResource flavorColor}" >
<Button Style="{StaticResource seeThrough}" Width="50" Height="70" x:Name="hamburgerMenu" Grid.Column="0" Grid.Row="0" BorderBrush="{x:Null}" Click="hamburger_Click" Cursor="Hand" HorizontalAlignment="Right">
<Rectangle Width="30" Height="30">
<Rectangle.Fill>
<DrawingBrush>
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" />
<GeometryDrawing Brush="White" Geometry="F1M13,11L3,11 3,13 13,13z M13,7L3,7 3,9 13,9z M13,5L3,5 3,3 13,3z" />
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
</Button>
<Button Click="default_Playlist_Click" x:Name="item1" Style="{StaticResource seeThrough}" Content="{Binding CurrentPlaylist.Name}" Visibility="Collapsed"></Button>
<Button Click="playlist_List_Click" x:Name="item2" Style="{StaticResource seeThrough}" Content="Playlists" Visibility="Collapsed"></Button>
<Button Click="full_Player_Click" x:Name="item3" Style="{StaticResource seeThrough}" Content="MaxPlayer" Visibility="Collapsed"></Button>
</StackPanel>
</Grid>
Player.XAML
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition />
</Grid.RowDefinitions>
<Slider x:Name="timeLine" Grid.Column="0" VerticalAlignment="Center"/>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal" Grid.Column="1" Grid.Row="2">
<Button x:Name="previousSong" Width="75" Height="30" Margin="10,0,10,20">
<<
</Button>
<Button Click="PlayPause" x:Name="playSong" Width="75" Height="30" Margin="10,0,10,20">
||
</Button>
<Button x:Name="nextSong" Width="75" Height="30" Margin="10,0,10,20">
>>
</Button>
</StackPanel>
</Grid>
Player.XAML.cs
public partial class Player : Page
{
private TimeSpan TotalTime;
DispatcherTimer timer;
private bool playerRunning = false;
private MainWindow mw;
MediaElement Media;
public Player(MainWindow mw)
{
this.mw = mw;
Media = mw.Media;
InitializeComponent();
timeLine.AddHandler(MouseLeftButtonUpEvent,
new MouseButtonEventHandler(SeekMediaPosition),
true);
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
}
public void timer_Tick(object sender, EventArgs e)
{
timeLine.Value = timeLine.Value + 1000;
}
private void PlayPause(object sender, RoutedEventArgs e)
{
if (Media.Source != null && playerRunning == true)
{
Media.Pause();
playSong.Content = ">";
playerRunning = false;
}
else if (Media.Source != null && playerRunning == false)
{
Media.Play();
playSong.Content = "||";
playerRunning = true;
}
}
private void Element_MediaOpened(object sender, EventArgs e)
{
timeLine.Maximum = Media.NaturalDuration.TimeSpan.TotalMilliseconds;
TotalTime = Media.NaturalDuration.TimeSpan;
timer.Start();
}
private void Element_MediaEnded(object sender, EventArgs e)
{
Media.Stop();
}
private void SeekMediaPosition(object sender, MouseButtonEventArgs args)
{
int val = (int)timeLine.Value;
Media.Position = new TimeSpan(0, 0, 0, 0, val);
}
}
This was my latest idea. But well as I thought it won't work.
I would appreciate if you guys would give a little poke towards the answer. :)

I'm not entirely sure what you mean by frames, so that may be the problem. But, this worked for me.
' Configure open file dialog box
Dim dlg As New Microsoft.Win32.OpenFileDialog()
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) & "iTunes\iTunes Media\Music"
dlg.FileName = "" ' Default file name
dlg.DefaultExt = ".txt" ' Default file extension
'dlg.Filter = "Music file (.mp3)|*.mp3;(.mp4)|*.mp4" ' Filter files by extension
dlg.Filter = "Music file (.mp3,.m4a)|*.mp3;*.m4a" ' Filter files by extension
' Show open file dialog box
Dim result? As Boolean = dlg.ShowDialog()
' Process open file dialog box results
If result = True Then
' Open document
Dim filename As String = dlg.FileName
Dim baseUri As New Uri(filename)
'MsgBox(filename)
myMediaElement.Stop()
myMediaElement.Source = baseUri
myMediaElement.Play()
End If
Also, I decided to stop using the media element all together because WMP (Actually, all Windows Media tech. I just uninstall it.) is nothing but a problem when you use it with iTunes. When I attempt my next one I will use a package that I found, easily find one in Tools -> Nuget Package Manager -> Manage NuGet Packages for Solution. Search for something like audio/music player.
The one I found, and was great for button beeps, was called NAudio.

Related

How to make a StackPanel visible only when the DragCompleted + Condition is matched

I am working on a UWP app in which my requirement is to show a StackPanel only when Drag is completed in a grid view and condition is met too.
I am making a drag and re-order like game. I want the StackPanel (Containing Result and Buttons) appear when not only a single drag is completed but all the items are sorted too.
I have got everything else working fine. Only StackPanel is problem. It appears just after on drag completed whether the condition is met or not.
Following are the screenshots, code and more briefing !
ScreenShot
XAML for GridView
<GridView Name="GameDisplay"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Grid.Row="1"
Grid.Column="1"
CanDrag="True"
CanDragItems="True"
CanReorderItems="True"
SelectionMode="Single"
AllowDrop="True"
DragItemsCompleted="GameDisplay_DragItemsCompleted">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Width="60"
Height="60"
Background="Black">
<TextBlock Text="{Binding}"
FontFamily="BriLliant"
FontSize="48"
FontWeight="light"
Foreground="White"
TextAlignment="Center"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal"
MaximumRowsOrColumns="10"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
XAML For StackPanel
<StackPanel Grid.Row="1" Grid.Column="1" Name="GameFinished" Background="#9900ff" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Height="auto">
<Grid Name="InnerGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Name="BtnsContainer" Grid.Column="1" Width="auto" Height="auto" Margin="0 10 0 0">
<Grid Name="BtnsGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Name="txtBannerType"
Width="auto"
Height="auto"
Grid.Row="0"
Text="Well Done !"
FontSize="72"
FontWeight="Bold"
FontFamily="BriLliant"
Foreground="White"
TextAlignment="Center"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<TextBlock Name="txtTimeSpent"
Width="200"
Height="auto"
Grid.Row="1"
Text=""
FontSize="48"
FontWeight="Light"
FontFamily="BriLliant"
Foreground="White"
TextAlignment="Center"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<TextBlock Name="txtScore"
Width="200"
Height="auto"
Grid.Row="2"
Text="Score : 0"
FontSize="48"
FontWeight="Light"
FontFamily="BriLliant"
Foreground="White"
TextAlignment="Center"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<TextBlock Name="txtBestScore"
Width="200"
Height="auto"
Grid.Row="3"
Text="Best Score : 0"
FontSize="48"
FontWeight="Light"
FontFamily="BriLliant"
Foreground="White"
TextAlignment="Center"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<Button Name="RestartGame"
Width="200"
Height="70"
Grid.Row="4"
Background="Black"
Content="Restart"
FontSize="48"
FontWeight="Bold"
FontFamily="BriLliant"
Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="0 20 0 0"
Click="RestartGame_Click"/>
<Button Name="MainMenu"
Width="200"
Height="70"
Grid.Row="5"
Background="Black"
Content="Main Menu"
FontSize="48"
FontWeight="Bold"
FontFamily="BriLliant"
Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="0 20 0 0"
Click="MainMenu_Click"/>
</Grid>
</StackPanel>
</Grid>
</StackPanel>
C# Events
private void Page_Loaded(object sender, RoutedEventArgs e)
{
lib.New(GameDisplay);//For Starting New Game
}
private void GameDisplay_DragItemsCompleted(ListViewBase sender, DragItemsCompletedEventArgs args)
{
lib.completed(GameDisplay);//When the tiles are re-ordered
}
Class that is handling BackEnd
class Library
{
//BackEnd for Math Game
private const int size = 5;
private const int total = size * size;
private DateTime timer;
private ObservableCollection<int> items = new ObservableCollection<int>();
private Random random = new Random((int)DateTime.Now.Ticks);
public void show(string content, string title)
{
IAsyncOperation<IUICommand> command = new MessageDialog(content, title).ShowAsync();
}
private List<int> select(int start, int finish, int total)
{
int number;
List<int> numbers = new List<int>();
while ((numbers.Count < total))
{
number = random.Next(start, finish + 1);
if ((!numbers.Contains(number)) || (numbers.Count < 1))
{
numbers.Add(number);
}
}
return numbers;
}
private bool winner()
{
return items.OrderBy(o => o).ToList().SequenceEqual(items.ToList());
}
private void layout(ref GridView grid)
{
timer = DateTime.UtcNow;
grid.IsEnabled = true;
grid.ItemsSource = null;
items = new ObservableCollection<int>();
List<int> numbers = select(1, total, total);
int index = 0;
while (index < numbers.Count)
{
items.Add(numbers[index]);
index++;
}
grid.ItemsSource = items;
}
public void New(GridView grid)
{
layout(ref grid);
}
public void completed(GridView grid)
{
string congo = "";
if (winner())
{
TimeSpan duration = (DateTime.UtcNow - timer).Duration();
congo = string.Format("Time: {0}:{1}:{2}", duration.Hours, duration.Minutes, duration.Seconds);
grid.IsEnabled = false;
}
}
}
Above is the game screen. When I drag and re-order a tile an event is fired in which a method runs until all the tiles are dragged and reordered according to the index of list that is containing all these numbers.
StackPanel only waits for one Drag. Is there any way to add StackPanel into the condition that checks for list sort?? Something like Data-Binding??
If you find anything missing, wrong or the question is already solved before. Please let me know explicitly !
Thanks...
Since you have already use winner() method to judge whether the game is ended and also invoke this in GameDisplay_DragItemsCompleted method. So actually the condition is already met in your completed method (every drag completed to judge whether game is over ). We just need to set the Visibility property of StackPanel to visible.
Update complete method as follows:
public void completed(GridView grid,StackPanel stackpanel)
{
string congo = "";
if (winner())
{
TimeSpan duration = (DateTime.UtcNow - timer).Duration();
congo = string.Format("Time: {0}:{1}:{2}", duration.Hours, duration.Minutes, duration.Seconds);
grid.IsEnabled = false;
stackpanel.Visibility = Visibility.Visible;
}
}
Update GameDisplay_DragItemsCompleted method as follows:
private void GameDisplay_DragItemsCompleted(ListViewBase sender, DragItemsCompletedEventArgs args)
{
lib.completed(GameDisplay,GameFinished);//When the tiles are re-ordered
}
Pay attention that in default the StackPanel should be collapsed. Update XAML code about StackPanel as follows:
<StackPanel Grid.Row="1" Grid.Column="1" Name="GameFinished" Background="#9900ff" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Height="auto" Visibility="Collapsed">
And you can reset the state for StackPanel and GridView when game restart. Code as follows:
private void RestartGame_Click(object sender, RoutedEventArgs e)
{
GameDisplay.IsEnabled = true;
GameFinished.Visibility = Visibility.Collapsed;
}
And the result:
The problem is, by this code in winner function
return items.OrderBy(o => o).ToList().SequenceEqual(items.ToList()); }
You just check if list items is equal to list items. It will always return true.
According to this msdn document orderBy orders the list itself does not return a copy of it.
If you are going to use this method, create another list to compare with curent list and keep that list sorted.
You may create two bool flags and check them in both methods OnDragComplete and OnChangeCondition like this:
private void OnDragComplete()
{
_isDragCompleted = true;
if (_isDragCompleted && _isConditionChanged)
{
CollapseStackPanel();
}
}
private void OnChangeCondition()
{
_isConditionChanged = true;
if (_isDragCompleted && _isConditionChanged)
{
CollapseStackPanel();
}
}
private void CollapseStackPanel()
{
_isDragCompleted = false;
_isConditionChanged = false;
StackPanel.Visibility = Visibility.Collapsed;
}

display a UserControl when click Button

I have created a ListViewTemplate as a UserControl,that I want to display it when I click on this Hamburger Button,this is my code:
Main.xaml:
<SplitView.Content >
<Grid Background="White" >
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#f0f0f0" >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="TrieButton" Margin="0" Content=""
Width="50" Background="Transparent" VerticalAlignment="Stretch" Click="TrieButton_Click" />
</StackPanel>
</Grid>
<Frame Grid.Row="1" x:Name="ContentFrame" Margin="0" />
</Grid>
</SplitView.Content>
And this is the code Behind:
Main.xaml.cs:
private void TrieButton_Click(object sender, RoutedEventArgs e)
{
ListViewTemplate c = new ListViewTemplate();
if (c.Visibility == Visibility.Visible)
{
c.Visibility = Visibility.Collapsed;
}
else
{
c.Visibility = Visibility.Visible;
}
}
this is my UserControl:
ListViewTemplate.xaml:
<Grid x:Name="FilterGrid" Background="Black">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0" >
<ListView x:Name="Liste" Background="Black" >
<ListViewItem >
<TextBlock Text="Nom" Foreground="#9d9e9e"/>
</ListViewItem>
<ListViewItem >
<TextBlock Text="Catégorie" Foreground="#9d9e9e"/>
</ListViewItem >
</ListView>
</StackPanel>
</Grid>
My problem is that this ListView UserControl is not shown when I click on the TrieButton,even I have increased the height of Grid
so please How can I correct my code,to have Listview showed when I click on TrieButton
thanks for help
Firstly: You didn't add the UserControl to your main XAML anywhere. You should add to XAML first like this:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:usercontrol="clr-namespace:WpfApplication1"
Then:
<Grid Background="White" x:Name="MGrid">
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="10" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#f0f0f0" >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="TrieButton" Margin="0" Content=""
Width="50" Background="Transparent" VerticalAlignment="Stretch" Click="TrieButton_Click" />
</StackPanel>
</Grid>
<Frame Grid.Row="1" x:Name="ContentFrame" Margin="0" />
<usercontrol:ListViewTemplate x:Name="c" Grid.Row="2" Visibility="Collapsed"></usercontrol:ListViewTemplate>
</Grid>
Secondly: You just created a new instance of a ListViewTemplate. You should find one that is placed in your XAML by using FindName method and then change the Visibility of it like this:
private void TrieButton_Click(object sender, RoutedEventArgs e)
{
ListViewTemplate c = MGrid.FindName("c") as ListViewTemplate;
c.Visibility = c.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
In response to the button click you are incorrectly creating a new instance of a ListViewTemplate object and then throwing it away.
I think that what you really want to do is something along these lines:
private void TrieButton_Click(object sender, RoutedEventArgs e)
{
ListViewTemplate c = (ListViewTemplate) Controls["Liste"];
if (c.Visibility == Visibility.Visible)
c.Visibility = Visibility.Collapsed;
else
c.Visibility = Visibility.Visible;
}
Here we retrieve the existing Control and change its visible/collapsed state.

WPF popup with textbox?

I am trying to create a control that displays search results as a user types something in a textbox. For this, I have a textbox and a popup that shows up when the user types something into it (just like a google search box). Like so,
<Grid> <TextBox Name="userEntry" /> <Popup /> </Grid>
Now when the user starts typing into the textbox i want the popup to show and stay open until the user focusses on some other ui control or if the text entered is empty.
I am unable to achieve this easily and was wondering if there are alternate better ways of doing this in wpf.
Regards
XAML :
<Window>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button x:Name="btn" Content="Open Search Window" Height="30" Width="150" Click="btn_Click"/>
<Popup x:Name="popup" PlacementTarget="{Binding ElementName=btn}" Placement="Bottom" Width="200" Height="100" Margin="0,20,0,0">
<Border BorderBrush="Black" BorderThickness="2" Background="AliceBlue">
<TextBox x:Name="txtBox" VerticalAlignment="Center" Margin="15,0,15,0"/>
</Border>
</Popup>
<TextBox x:Name="focusTarger" Text="Focus Me !" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" TextAlignment="Center" FontSize="16"/>
</Grid>
</Window>
CS :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GotFocus += MainWindow_GotFocus;
}
void MainWindow_GotFocus(object sender, RoutedEventArgs e)
{
FrameworkElement element = (FrameworkElement)e.OriginalSource;
if (txtBox == element || popup == element || element.Parent == popup)
return;
popup.IsOpen = !string.IsNullOrEmpty(txtBox.Text);
}
private void btn_Click(object sender, RoutedEventArgs e)
{
popup.IsOpen = true;
}
}

Windows phone 8 ListBox becomes empty after loading a lot of data

In my WP8 application I have a listbox which performs Lazy load. All is working fine except one thing. Sometimes after scrolling up or down, even when data is the same, my listbox becomes empty. I analized the used memory using "Windows phone application analyses" and got the maximum used memory 100MB. So there is no problem with memory. Also aplication does not crash after becoming listbox empty. Do you have any ideas why these happen?
Here is my XAML:
<ListBox Name="lbCollections" LayoutUpdated="lbCollectins_LayoutUpdated">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Background="White" Margin="20">
<Grid Margin="15,5,15,5">
<Grid.RowDefinitions>
<RowDefinition Height="45"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="{Binding CategoryName}" Foreground="Black" Style="{StaticResource EmptyListHeaderStyle}"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding CreatedOn, StringFormat='{}{0:MM dd, yyyy}'}" Foreground="Gray" Style="{StaticResource PhoneTextSmallStyle}"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding PhotosCountTxt}" Foreground="Gray" Style="{StaticResource PhoneTextSmallStyle}"></TextBlock>
</Grid>
<Grid Height="150">
<Grid.Resources>
<conv:ImageConverter x:Key="ImageConverter" />
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Name="img1" Source="{Binding Photos, Converter={StaticResource ImageConverter}, ConverterParameter=0}" Width="150" Height="150" Margin="5"/>
<Image Grid.Column="1" Name="img2" Source="{Binding Photos, Converter={StaticResource ImageConverter}, ConverterParameter=1}" Width="150" Height="150" Margin="5"></Image>
<Image Grid.Column="2" Name="img3" Source="{Binding Photos, Converter={StaticResource ImageConverter}, ConverterParameter=2}" Width="150" Height="150" Margin="5"></Image>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is the code behind:
private async void LoadContent()
{
if (loadingProgress)
{
return;
}
else
{
try
{
loadingProgress = true;
CollectionResponse collectionResp = await CollectionService.IterateAsync(MapPoint, "", dtStart, dtEnd, filterCategoryId, loadedCollectionsCount, collectionsCountToLoadAtOnce, 4, (int)TimeZoneInfo.Local.BaseUtcOffset.TotalMinutes, AppSettings.Invisible, AppSettings.Token);
if (collectionResp.Collections.Count == 0)
{
endOfList = true;
}
else
{
loadedCollectionsCount += collectionResp.Collections.Count;
if (!(lbCollections.ItemsSource is List<CollectionModel>))
{
lbCollections.ItemsSource = new List<CollectionModel>();
}
(lbCollections.ItemsSource as List<CollectionModel>).AddRange(collectionResp.Collections);
//lbCollections.ItemsSource = collectionResp.Collections;
}
}
catch
{
}
finally
{
loadingProgress = false;
}
}
}
private void lbCollectins_LayoutUpdated(object sender, EventArgs e)
{
ScrollBar scrollBar = FindChildOfType<ScrollBar>(lbCollections).Where(sb=>sb.Orientation == System.Windows.Controls.Orientation.Vertical).FirstOrDefault();
if (scrollBar != null)
{
bool endOfScroll = scrollBar.Maximum > 0 && scrollBar.Value > 0 && scrollBar.Maximum - scrollBar.Value < 10;
if (!endOfList && endOfScroll)
{
LoadContent();
}
}
}
static List<T> FindChildOfType<T>(DependencyObject root) where T : class
{
List<T> foundObjects = new List<T>();
var queue = new Queue<DependencyObject>();
queue.Enqueue(root);
while (queue.Count > 0)
{
DependencyObject current = queue.Dequeue();
for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; i >= 0; i--)
{
var child = VisualTreeHelper.GetChild(current, i);
var typedChild = child as T;
if (typedChild != null)
{
foundObjects.Add(typedChild);
}
queue.Enqueue(child);
}
}
return foundObjects;
}
Two things to do.
Take a look at this blog about why the ListBox goes blank. Most likely the problem is the images you are showing. You can easily fix by doing the following
Start using the LongListSelector for WP8 (not the WP Toolkit version!) It is designed for fast scrolling even with images

How to Show ProgressBar over VideoBrush

I have a feature that allows a user to switch between the FrontFacing and Primary cameras on a device. During the switching process, I'd like to show a ProgressBar and TextBlock to the user. For some reason, I cannot get these to show up in the View, and the only thing that shows during the switching process is a frozen image of the nonrotated VideoBrush
MainPage.xaml
<Grid.RowDefinitions>
<RowDefinition Height="72"/>
<RowDefinition Height="*"/>
<RowDefinition Height="68"/>
<RowDefinition Height="72"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="72"/>
<ColumnDefinition Width=".33*"/>
<ColumnDefinition Width=".33*"/>
<ColumnDefinition Width=".33*"/>
<ColumnDefinition Width="72"/>
</Grid.ColumnDefinitions>
<!-- Center this on the screen -->
<Canvas x:Name="VideoCanvas" Grid.Row="0" Grid.RowSpan="4" Grid.ColumnSpan="5"
VerticalAlignment="Center" HorizontalAlignment="Center">
<Canvas.Background>
<VideoBrush x:Name="videoBrush">
<VideoBrush.RelativeTransform>
<CompositeTransform x:Name="videoBrushTransform"
CenterX="0.5" CenterY="0.5"/>
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
</Canvas>
...
<StackPanel Grid.Row="1" Grid.ColumnSpan="5" VerticalAlignment="Center">
<ProgressBar x:Name="progressIndicator" IsIndeterminate="False" Background="Transparent"/>
<TextBlock x:Name="modeChangeTextBlock" Margin="12"
VerticalAlignment="Top" HorizontalAlignment="Center" FontSize="28"
Foreground="{StaticResource PhoneSubtleBrush}"/>
</StackPanel>
MainPage.xaml.cs
void sensor_Click(object sender, EventArgs e)
{
CameraType type = camera.CameraType;
//Switch to other camera, if available
if(type == CameraType.Primary)
{
if(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)
{
ShowProgress("Switching cameras");
UninitializeCamera();
InitializeCamera(CameraType.FrontFacing);
HideProgress();
}
}
else
{
if(PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true)
{
ShowProgress("Switching cameras");
UninitializeCamera();
InitializeCamera(CameraType.Primary);
HideProgress();
}
}
}
...
private void ShowProgress(String msg)
{
progressIndicator.IsIndeterminate = true;
modeChangeTextBlock.Text = msg;
//progressIndicator.Visibility = Visibility.Visible;
}
private void HideProgress()
{
progressIndicator.IsIndeterminate = false;
modeChangeTextBlock.Text = "";
//progressIndicator.Visibility = Visibility.Collapsed;
}
EDIT * added below existing xaml code for testing
<Rectangle x:Name="cameraSwitchingFill" Visibility="Visible"
Fill="{StaticResource SelfiePageBackgroundColorBrush}"
Grid.Row="0" Grid.Column="0" Grid.RowSpan="4" Grid.ColumnSpan="5"/>
<StackPanel Grid.Row="1" Grid.ColumnSpan="5" VerticalAlignment="Center">
<ProgressBar x:Name="progressIndicator" IsIndeterminate="True" Background="Transparent"/>
<TextBlock x:Name="modeChangeTextBlock" Margin="12"
VerticalAlignment="Top" HorizontalAlignment="Center" FontSize="28"
Foreground="{StaticResource PhoneSubtleBrush}" Text="test"/>
</StackPanel>
The added edit is an attempt to see why the progressbar is not showing during camera switching. Setting everything to be seen on the screen, when first navigating to this page all I see is the cameraSwitchingFill rectangle, with no ProgressBar or TextBlock over it (although in the designer I can see these just fine). Upon switching the cameras, (as expected) I see the rectangle but no ProgressBar or TextBlock.
I then went back to not show the edits and modified
void sensor_Click(object sender, EventArgs e)
{
//Switch to other camera, if available
CameraType type = camera.CameraType;
if(type == CameraType.Primary)
{
if(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)
{
ShowProgress(AppResources.CapturePage_SwitchingCameras);
cameraSwitchingFill.Visibility = Visibility.Visible;
UninitializeCamera();
InitializeCamera(CameraType.FrontFacing);
cameraSwitchingFill.Visibility = Visibility.Collapsed;
HideProgress();
}
}
else
{
if(PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true)
{
ShowProgress(AppResources.CapturePage_SwitchingCameras);
cameraSwitchingFill.Visibility = Visibility.Visible;
UninitializeCamera();
InitializeCamera(CameraType.Primary);
cameraSwitchingFill.Visibility = Visibility.Collapsed;
HideProgress();
}
}
}
So the results are when I permanently make the rectangle and Progressbar show on the screen, Only the rectangle is shown until the first camera switch click event occurs, and thereafter neither the rectangle or progressbar will show. Also, the frozen image remains on the screen during the switching even though the rectangle and progressbar, declared below the videobrush implementation in xaml, are set to visible during this time.
May this will help you. try this
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Center this on the screen -->
<Canvas x:Name="VideoCanvas" Grid.Row="0" >
<Canvas.Background>
<VideoBrush x:Name="videoBrush" >
<VideoBrush.RelativeTransform>
<CompositeTransform x:Name="videoBrushTransform"
CenterX="0.5" CenterY="0.5"/>
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
</Canvas>
<StackPanel Grid.Row="0" VerticalAlignment="Center">
<TextBlock x:Name="modeChangeTextBlock" Margin="12" VerticalAlignment="Top" HorizontalAlignment="Center" FontSize="28" Foreground="{StaticResource PhoneSubtleBrush}"/>
<ProgressBar x:Name="progressIndicator" IsIndeterminate="False" Grid.RowSpan="4" />
</StackPanel>
</Grid>
There is nothing wrong in the declarations. Its just that the order at which you are making the declarations isnt correct.
the overlapping in grid is done by the order at which you write your xaml
In the xaml given the Panel containing textblock and progressbar is placed at first position and then the panel containing the Videobrush comes which overlaps the first panel(The main reason behind the invisibility). So, if you want the panel to be visible just declare it one level below the panel containing the videobrush. This woulf help the panel having progressbar to overlap the panel containing the videobrush.
and hence the updated declarations now becomes
<Grid.RowDefinitions>
<RowDefinition Height="72"/>
<RowDefinition Height="*"/>
<RowDefinition Height="68"/>
<RowDefinition Height="72"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="72"/>
<ColumnDefinition Width=".33*"/>
<ColumnDefinition Width=".33*"/>
<ColumnDefinition Width=".33*"/>
<ColumnDefinition Width="72"/>
</Grid.ColumnDefinitions>
<!-- Center this on the screen -->
<Canvas x:Name="VideoCanvas" Grid.Row="0" Grid.RowSpan="4" Grid.ColumnSpan="5">
<Canvas.Background>
<VideoBrush x:Name="videoBrush" >
<VideoBrush.RelativeTransform>
<CompositeTransform x:Name="videoBrushTransform"
CenterX="0.5" CenterY="0.5"/>
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
</Canvas>
<StackPanel Grid.Row="1" Grid.ColumnSpan="5" VerticalAlignment="Center">
<ProgressBar x:Name="progressIndicator" IsIndeterminate="True" Background="Transparent"/>
<TextBlock x:Name="modeChangeTextBlock" Margin="12" Text="loading"
VerticalAlignment="Top" HorizontalAlignment="Center" FontSize="28"
Foreground="White"/>
</StackPanel>
Hope this helps.

Categories

Resources