Silverlight ComboBox value does not fall within the expected range - c#

We are developing a silverlight 5 application. Within our application we use the combobox control.
When a combobox is open (IsDropDownOpen = true) and the combobox has a selected value and the combobox is removed and readded in the visual tree during a SizeChange event, the following exception is thrown: "value does not fall within the expected range".
I managed to reproduce this error in the example code. Is this a Silverlight 5 issue/bug or am I doing something wrong?
<UserControl x:Class="SilverlightApplication3.MainPage"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
</Grid>
</UserControl>
code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
private ComboBox combo;
private Button b;
public MainPage()
{
InitializeComponent();
combo = new ComboBox() { Width = 100, Height = 20 };
combo.Items.Add(new ComboBoxItem() { Content = "Jaar", IsSelected = true});
LayoutRoot.Children.Add(combo);
LayoutRoot.SizeChanged += new SizeChangedEventHandler(LayoutRoot_SizeChanged);
b = new Button() { Content = "Crash Me" };
b.Click += new RoutedEventHandler(b_Click);
Grid.SetRow(b, 1);
LayoutRoot.Children.Add(b);
}
void b_Click(object sender, RoutedEventArgs e)
{
combo.IsDropDownOpen = true;
Width = 500;
}
void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
{
LayoutRoot.Children.Clear();
LayoutRoot.Children.Add(b);
LayoutRoot.Children.Add(combo);
}
}
}

Related

C# WPF image load like progressbar

I'v a progressbar and an image.
When Progress Bar value is 50, image loaded by 50%.
I tried to add image as the progressbar foreground, but it have green shade. So ugly.
How can I do this?
To run this sample, you need a snake image which you can get from http://res.freestockphotos.biz/pictures/16/16242-illustration-of-a-green-snake-pv.png. I have used this url directly, but your should download image first and then use it.
You need a control template for your ProgressBar because you want to show percentage status too.
Otherwise normal ProgressBar would do.
Code can be used as is :
<Window x:Class="WpfControlTemplates._32794074.Win32794074"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Win32794074" Height="600" Width="1000">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="397*"/>
<RowDefinition Height="173*"/>
</Grid.RowDefinitions>
<ProgressBar x:Name="PBarCustom" Width="958" Height="200" Maximum="958" Value="958" Foreground="#FFE6E61F" Margin="17,185,17,11.932" ValueChanged="PBarCustom_ValueChanged">
<ProgressBar.Background>
<ImageBrush ImageSource="http://res.freestockphotos.biz/pictures/16/16242-illustration-of-a-green-snake-pv.png"/>
</ProgressBar.Background>
<ProgressBar.Template>
<ControlTemplate>
<Grid Background="{TemplateBinding Background}">
<Rectangle x:Name="Thumb" HorizontalAlignment="Left" Fill="#FFC5EA1F" Stroke="#FF0DB442" Width="{TemplateBinding Width}" />
<Ellipse Fill="#FF7DEEDE" Height="124" Stroke="#FF0DB442" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center" Opacity="0.3"/>
<Label x:Name="tbStatus" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontWeight="Bold" FontSize="75" Foreground="#FF21BD76" Content="0" />
</Grid>
</ControlTemplate>
</ProgressBar.Template>
</ProgressBar>
<Button x:Name="BtnLoadSnake" Content="Load Snake" HorizontalAlignment="Left" Margin="462,14.068,0,0" VerticalAlignment="Top" Width="75" Click="BtnLoadSnake_Click" Grid.Row="1"/>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace WpfControlTemplates._32794074
{
/// <summary>
/// Interaction logic for Win32794074.xaml
/// </summary>
public partial class Win32794074 : Window
{
public Win32794074()
{
InitializeComponent();
}
DispatcherTimer timer;
private void BtnLoadSnake_Click(object sender, RoutedEventArgs e)
{
BtnLoadSnake.IsEnabled = false;
PBarCustom.Value = PBarCustom.Maximum;
Rectangle thumb = (Rectangle)PBarCustom.Template.FindName("Thumb", PBarCustom);
thumb.Width = PBarCustom.Value;
Label status = (Label)PBarCustom.Template.FindName("tbStatus", PBarCustom);
status.Content = ((int)(100 - ((100 * PBarCustom.Value) / PBarCustom.Maximum))).ToString();
Dispatcher disp = PBarCustom.Dispatcher;
EventHandler pBarCallbackHandler = new EventHandler(pBarCallback);
timer = new DispatcherTimer(TimeSpan.FromSeconds(0.5), DispatcherPriority.Normal, pBarCallback, disp);
}
private void pBarCallback(object sender, EventArgs e)
{
PBarCustom.Value -= 13;
Rectangle thumb = (Rectangle)PBarCustom.Template.FindName("Thumb", PBarCustom);
thumb.Width = PBarCustom.Value;
Label status = (Label)PBarCustom.Template.FindName("tbStatus", PBarCustom);
status.Content = ((int)(100 - ((100 * PBarCustom.Value) / PBarCustom.Maximum))).ToString();
if (PBarCustom.Value == 0)
timer.Stop();
}
private void PBarCustom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if(e.NewValue == 0)
BtnLoadSnake.IsEnabled = true;
}
}
}
i had similar scenario.
if you want the scroll bar to be just a rectangle,
easiest way to make it:
1- add an image to your window.
2- put a grid on it in such a way that the grid hides the image.
3- programatically change the width or height of the grid.
tell me if you needed an example code.

pull down to refresh listbox in windows phone 8.1 Silverlight

I am new in windows phone development. i want to try to implement pull down to refresh page. i use listbox under scrollviewer i am having a problem while implement in windows phone 8.1 silverlight application. here is my code
MainPage.xaml
<phone:PhoneApplicationPage
x:Class="PullDownToScroll.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid>
<ScrollViewer Name="OuterScroll" Loaded="OuterScroll_Loaded" LayoutUpdated="OuterScroll_ViewChanged">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Background="GreenYellow">
<Image Source="Assets/down13.png" Height="40" Width="40" HorizontalAlignment="Left" Margin="20,0,0,0">
<Image.RenderTransform>
<RotateTransform x:Name="RefreshIndicatiorRotateTransform" CenterX="20" CenterY="20"/>
</Image.RenderTransform>
</Image>
<TextBlock Name="RefreshIndicatiorTextBlock" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="80,0,0,0" Width="200" Foreground="Black"/>
</Grid>
<ListBox Name="InnerListView" Grid.Row="1">
</ListBox>
</Grid>
</ScrollViewer>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PullDownToScroll.Resources;
using System.Windows.Media;
namespace PullDownToScroll
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.InitializeComponent();
InnerListView.Height = ApplicationView.GetForCurrentView().VisibleBounds.Height;
GenerateRandomListViewItem();
this.NavigationCacheMode = NavigationCacheMode.Required;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
public void GenerateRandomListViewItem()
{
InnerListView.Items.Clear();
Random rand = new Random();
for (int i = 0; i < 20; i++)
{
ListBox item = new ListBox();
item.Background = new SolidColorBrush(Color.FromArgb(255, (byte)rand.Next(0, 255), (byte)rand.Next(0, 255), (byte)rand.Next(0, 255)));
item.Height = rand.NextDouble() * 150;
item.Margin = new Thickness(0, 8, 0, 8);
InnerListView.Items.Add(item);
}
}
private void OuterScroll_Loaded(object sender, RoutedEventArgs e)
{
OuterScroll.ChangeView(null, 60, null, false);
}
private void OuterScroll_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
if (!e.IsIntermediate)
{
if (OuterScroll.VerticalOffset < 60)
{
if (OuterScroll.VerticalOffset <= 0.5)
OuterScroll.ChangeView(null, 60, null, false);
else
OuterScroll.ChangeView(null, 60, null);
}
if (OuterScroll.VerticalOffset <= 0.5)
{
GenerateRandomListViewItem();
}
}
else
{
double angle = (65 - OuterScroll.VerticalOffset) * 180 / 65;
RefreshIndicatiorRotateTransform.Angle = angle;
}
if (OuterScroll.VerticalOffset == 0)
RefreshIndicatiorTextBlock.Text = "Release to refresh";
else
RefreshIndicatiorTextBlock.Text = "Pull to refresh";
}
}
}
In MainPage.xaml.cs i found an error
Error 1 The type or namespace name 'ScrollViewerViewChangedEventArgs' could not be found (are you missing a using directive or an assembly reference?)
how should i resolve this problem ?? please share you suggestion.
Thanks in advance.
Best way to refresh view/screen use Application bar. Put refresh icon in Application bar and on icon click refresh your view/screen.
This link is help full for how to use Appication bar

WPF - Webbrowser - getElementById

In a WPF application, I have a webbrowser called WebBrowser1. This refers to an HTML page which contains a TextArea to which users can input text.
<html>
<body>
<textarea class="myStudentInput" id="myStudentInput1">
Text to be copied
</textarea>
</body>
</html>
I wish to get this text and potentially also set this text.
I have tried something similar to the javascript way of writing it:
document.getElementById("myStudentOutput1").innerHTML;
such as
HtmlElement textArea = webBrowser1.Document.All["myStudentInput1"];
dynamic textArea = WebBrowser1.Document.GetElementsByID("myStudentInput1").InnerText;
but it doesn't work.
The following solution in Visual Studio 2015 WPF Application works for me.
First, add a reference to the Microsoft HTML COM Library. This is on the COM tab, when you do an "Add Reference" in your project.
Then add the code:
<Window x:Class="WpfApplication3.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:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="800">
<Grid>
<WebBrowser x:Name="WebBrowser1" HorizontalAlignment="Left" Height="480" Margin="10,10,0,0" VerticalAlignment="Top" Width="770" Source="E:\Others\Dropbox\Programming\Questions.html"/>
<Button x:Name="mySetQuestionButton" Content="Set Question" HorizontalAlignment="Left" Margin="200,520,0,0" VerticalAlignment="Top" Width="75" Click="mySetQuestion"/>
<Button x:Name="myGetAnswerButton" Content="Get Answer" HorizontalAlignment="Left" Margin="350,520,0,0" VerticalAlignment="Top" Width="75" Click="myGetAnswer"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="600,520,0,0" TextWrapping="Wrap" Text="Hello2" VerticalAlignment="Top"/>
</Grid>
</Window>
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void mySetQuestion(object sender, EventArgs e)
{
mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
mshtml.IHTMLElement textArea = document.getElementById("myQuestion1");
textArea.innerHTML = "What is 1+1?";
}
private void myGetAnswer(object sender, EventArgs e)
{
mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
mshtml.IHTMLElement textArea = document.getElementById("myStudentInput1");
textBlock.Text = textArea.innerHTML;
}
}
}
but it doesn't work.
I have no idea what that could possibly mean. All you can get is a code snippet that does work:
public partial class Form1 : Form {
private WebBrowser webBrowser1;
private Button button1;
public Form1() {
button1 = new Button { Text = "Test" };
button1.Click += button1_Click;
this.Controls.Add(button1);
webBrowser1 = new WebBrowser { Dock = DockStyle.Fill };
webBrowser1.DocumentText = #"<html><body><textarea class=""myStudentInput"" id=""myStudentInput1"">Text to be copied</textarea></body></html>";
this.Controls.Add(webBrowser1);
}
private void button1_Click(object sender, EventArgs e) {
var elem = webBrowser1.Document.GetElementById("myStudentInput1");
MessageBox.Show(elem.InnerText);
}
}
Which produces:

Dynamically preventing a TextBox from getting focus

I have a System.Windows.Controls.TextBox which I would like to behave as follows: When you click it, it is determined dynamically if the TextBox gets focus or not. Here's a toy application which contains a failed attempt at accomplishing this:
<!-- MainWindow.xaml -->
<Window x:Class="Focus.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></RowDefinition>
</Grid.RowDefinitions>
<Label Name="myLabel" Grid.Row="0" Background="Red"></Label>
<TextBox Name="myTextbox" Grid.Row="1" Background="Green"></TextBox>
</Grid>
</Window>
// MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;
namespace Focus
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
}
private static readonly Random myRandom = new Random();
private void myTextbox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
int randomInt = myRandom.Next(0, 2); // 0 or 1
myLabel.Content = randomInt;
if(randomInt==0)
{
// PREVENT FOCUS - INSERT CODE HERE. (The line below is a failed attempt.)
FocusManager.SetFocusedElement(this, myLabel);
}
}
}
}
The following code seems to do the trick:
// PREVENT FOCUS - INSERT CODE HERE.
myLabel.Focusable = true;
myLabel.Focus();
myLabel.Focusable = false;
I also changed this line of code:
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
into this:
myTextbox.GotFocus += myTextbox_GotKeyboardFocus;
I hope you know that you hooked up to the keyboard focus (TAB key).
void textBox1_GotFocus(object sender, System.EventArgs e)
{
if (!this.checkBox1.Checked)
this.checkBox1.Focus();
else
this.textBox1.Focus();
}

Creating a simple seeking media player with MediaElement in WPF

I have also posted this on MSDN forums - i hope its not a problem.
I am basically trying to create a WPF based video player which allows you to seek within media. I'm trying to implement it using MediaTimeline (i know i can change the Position property, but i had other issues which i'll post in a separate question). XAML and code-behind are below.
Thanks for looking...
MainWindow.xaml
<Window x:Class="WpfApplication5.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"/>
</Grid.RowDefinitions>
<MediaElement x:Name="mediaElement" Width="320" Height="240" Margin="4" LoadedBehavior="Manual"/>
<Slider x:Name="slider" Grid.Row="1" Margin="4"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace WpfApplication5
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var tl = new MediaTimeline(new Uri(#"c:\temp\!numa.wmv"));
mediaElement.Clock = tl.CreateClock(true) as MediaClock;
mediaElement.MediaOpened += (o, e) =>
{
slider.Maximum = mediaElement.NaturalDuration.TimeSpan.Seconds;
mediaElement.Clock.Controller.Pause();
};
slider.ValueChanged += (o, e) =>
{
mediaElement.Clock.Controller.Seek(TimeSpan.FromSeconds(slider.Value), TimeSeekOrigin.BeginTime);
};
}
}
}
You need to set ScrubbingEnabled="True" on MediaElement to have it update during seeks.
the MediaOpened event should actually be setting the maximum value to .TotalSeconds, and you should also set ScrubbingEnabled to True as jesperll pointed out.

Categories

Resources