Silverlight Without XAML - Images Will Not Render - silverlight

I have a Silverlight application in which I'm not using XAML. I have a basic application with the following code in Application_Startup:
private void Application_Startup(object sender, StartupEventArgs e)
{
Grid g = new Grid();
g.Children.Add(new Image { Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://sstatic.net/so/img/sprites.png", UriKind.Absolute)) });
this.RootVisual = g;
}
This code will not render the specified image. If however, the App.Xaml file is modified to define the RootVisual in the Xaml the following works:
xaml:
<Application.RootVisual>
<Grid>
</Grid>
</Application.RootVisual>
code:
private void Application_Startup(object sender, StartupEventArgs e)
{
((Grid)this.RootVisual).Children.Add(new Image { Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://sstatic.net/so/img/sprites.png", UriKind.Absolute)) });
}
I don't see why one would work and the other not. I have the same behavior using a UserControl as well (using Content instead of Childern of course).
From what I understand, there should be not XAML requirement. Is there something I'm missing?

The difference is in the first case you are setting the RootVisual to be a Grid, but in the second your grid is a child element.
On the MSDN page for the RootVisual property it shows the following example:
this.RootVisual = new Page();
so if you create a Page and then add your Grid to that page it should work.
Page page = new Page();
page.Content = g;
this.RootVisual = page;

Related

WPF spell checking not loading a custom dictionary in a tab

If I globally enable spell checking in App.xaml...
<Application.Resources>
<Style TargetType="TextBox">
<Setter Property="SpellCheck.IsEnabled"
Value="True" />
</Style>
</Application.Resources>
...then I get red underlines and spell checking in all textboxes in the application, irrespective of where they are.
If I want to add a custom dictionary, then I have to use code similar to the one shown in this SO answer, and then call it as follows...
public MainWindow() {
InitializeComponent();
Loaded += (_, __) => Helpers.SetCustomDictionary(this);
}
(code for helper method shown lower down)
This works fine for textboxes that are shown when the window first loads, but if I have a tab control, and the default tab has a textbox, then the custom dictionary is not applied.
I tried calling Helpers.SetCustomDictionary(this) when the tab loaded, but that didn't work either. I can see that the method is called when the window loads, and my guess is that at that stage, the tab's contents haven't been created, so the method doesn't find them to set the custom dictionary.
The only thing I found that worked was calling it when the individual textbox itself was loaded. However, this is painful, as I have to do this for every single textbox individually.
Anyone know of a way to get the custom dictionary working for textboxes that are not visible when the window first loads?
Thanks
P.S. Here is the code for the helper method, which uses the FindAllChildren() method shown in the linked SO reply...
public static void SetCustomDictionary(DependencyObject parent) {
Uri uri = new Uri("pack://application:,,,/CustomDictionary.lex");
List<TextBox> textBoxes = new List<TextBox>();
FindAllChildren(parent, ref textBoxes);
foreach (TextBox tb in textBoxes) {
if (tb.SpellCheck.IsEnabled && !tb.SpellCheck.CustomDictionaries.Contains(uri)) {
tb.SpellCheck.CustomDictionaries.Add(uri);
}
}
}
There is probably a better solution but you could use OnStartup event of your App.xaml.cs to set the dictionary for every TextBox when it loads with a single event handler:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
EventManager.RegisterClassHandler(typeof(TextBox), FrameworkElement.LoadedEvent, new RoutedEventHandler(TextBox_OnLoaded));
}
private void TextBox_OnLoaded(object sender, RoutedEventArgs e)
{
// Set custom dictionary here.
}
}
Whilst Dean Kuga's answer looked promising, it didn't work for me. After some more searching, it seems that there is a bug that prevents the Loaded event from being fired in most cases. In a comment to the answer to the SO question where I saw this mentioned, Marcin Wisnicki linked to some code he wrote that works around the issue.
As I only want this to work for textboxes, I simplified his code a little. In case it helps anyone, here is my simplified code...
public partial class App {
protected override void OnStartup(StartupEventArgs e) {
base.OnStartup(e);
EventManager.RegisterClassHandler(typeof(Window),
FrameworkElement.SizeChangedEvent, new RoutedEventHandler(OnSizeChanged));
EventManager.RegisterClassHandler(typeof(TextBox),
FrameworkElement.LoadedEvent, new RoutedEventHandler(OnLoaded), true);
}
private static void OnSizeChanged(object sender, RoutedEventArgs e) {
SetMyInitialised((Window)sender, true);
}
private static void OnLoaded(object sender, RoutedEventArgs e) {
if (e.OriginalSource is TextBox) {
TextBox tb = (TextBox)e.OriginalSource;
Helpers.SetCustomDictionaryTextBox(tb);
}
}
#region MyInitialised dependency property
public static readonly DependencyProperty MyInitialisedProperty =
DependencyProperty.RegisterAttached("MyInitialised",
typeof(bool),
typeof(App),
new FrameworkPropertyMetadata(false,
FrameworkPropertyMetadataOptions.Inherits,
OnMyInitialisedChanged));
private static void OnMyInitialisedChanged(DependencyObject dpo,
DependencyPropertyChangedEventArgs ev) {
if ((bool)ev.NewValue && dpo is FrameworkElement) {
(dpo as FrameworkElement).Loaded += delegate { };
}
}
public static void SetMyInitialised(UIElement element, bool value) {
element.SetValue(MyInitialisedProperty, value);
}
public static bool GetMyInitialised(UIElement element) {
return (bool)element.GetValue(MyInitialisedProperty);
}
#endregion MyInitialised
}
Being English, I changed "Initialized" to "Initialised", but other than that, the DP code is the same.
Hope this helps someone.

How show contents of wpf window in stack panel

i want to show contents of window in wpf when click on button
i think will use container controls like stake panel but doesn't work
private void RibbonButton_Click(object sender, RoutedEventArgs e)
{
Window1 w1 = new Window1();
stkShow.Children.Add(w1);
}
You need to use the content of the window you want to use as child.
This worked for me.
private void RibbonButton_Click(object sender, RoutedEventArgs e)
{
Window1 Child = new Window1();
StkPanelContent.Children.Clear();
object content = Child.Content;
Child.Content = null;
Child.Close();
this.stkShow.Children.Add(content as UIElement);
}
I hope it helps.

Silverlight Toolkit Accordion ScrollViewer

I am populating my Accordion with items from my database. I have also wrapped my Accordion in a ScrollViewer:
<ScrollViewer Name="LayoutScrollViewer">
<toolkit:Accordion Name="ItemsAccordion" ItemTemplate="{StaticResource AccordionHeaderTemplate}" ContentTemplate="{StaticResource AccordionContentTemplate}"></toolkit:Accordion>
</ScrollViewer>
However, I cannot find a way to initially show the VerticalOffset of the ScrollViewer to 0. It keeps on scrolling to the bottom whenever my database content is finished loading. I have tried in the codebehind:
void CatalogItem_Loaded(object sender, RoutedEventArgs e)
{
WebServiceClient client = new WebServiceClient();
client.GetCatalogItemsAsync(countID);
client.GetCatalogItemsCompleted += new EventHandler<GetCatalogItemsCompletedEventArgs>(client_GetCatalogItemsCompleted);
}
void client_GetCatalogItemsCompleted(object sender, GetCatalogItemsCompletedEventArgs e)
{
ItemsAccordion.ItemsSource = e.Result;
UpdateScrollViewer();
}
private void UpdateScrollViewer()
{
LayoutScrollViewer.ScrollToVerticalOffset(0);
}
This doesn't work, though. I have also tried, in UpdateScrollViewer() to do:
LayoutScrollViewer.IsHitTestVisible = false;
LayoutScrollViewer.IsHitTestVisible = true;
which doesn't work either. If I leave it as IsHitTestVisible= false, then it works as I would like; but I also want user interaction with the Accordion, so this isn't a permanent solution.
I hate to do this but thy the following:
void client_GetCatalogItemsCompleted(object sender, GetCatalogItemsCompletedEventArgs e)
{
ItemsAccordion.ItemsSource = e.Result;
UpdateLayout();
UpdateScrollViewer();
}

Open MediaElement in FullScreen

There is a MediaElement in my silverLight4 Application that plays videos.
There are also other controls in the form (listbox, buttons etc...).
When vieweing a Video, i want the option to switch to Fullscreen, but only the video and not all the form (something like youtube), is there a way to switch just the 'MediaElement' control to fullscreen?
Make your MediaElement the RootVisual of the app. Since you can't change the RootVisual once it's assigned you need to do something like so
private MainPage _mainPage = new MainPage();
private MediaElement _media = new MediaElement();
private void Application_Startup(object sender, StartupEventArgs e)
{
Grid grid = new Grid();
grid.Children.Add(_mainPage);
this.RootVisual = grid;
}
public void FullscreenVideo()
{
(this.RootVisual as Grid).Children.Clear();
(this.RootVisual as Grid).Children.Add(_media);
Application.Current.Host.Content.IsFullScreen = true;
}
If you call FullscreenVideo it should load your MediaElement into a fullscreen window

How can i navigate one xaml page to another?

i have 2 page i need to navigate mainpage.xaml to login.page xaml but it throws me
Object reference not set to an instance of an object. in Root.Children.Clear();....
i added this codes in App.xaml:
private void Application_Startup(object sender, StartupEventArgs e)
{
Grid myGrid = new Grid();
myGrid.Children.Add(new MainPage());
this.RootVisual = myGrid;
}
and than i adde some codes on main.xaml to navigate to LoginUI.xaml
namespace Gen.CallCenter.UI
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Grid Root = ((Grid)(this.Parent));
Root.Children.Clear();
Root.Children.Add(new LoginUI());
}
}
}
How can i navigate main.xaml to LoginUI.xaml ?
Let's suppose you are viewing the MainPage.xaml then you want to open another xaml page called newPage.xaml by clicking on a Button or an ImageEdit in the MainPage.xaml, here's the quick solution that you should write inside the MainPage.xaml.cs:
private void imageEdit1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
newPage mynewPage = new newPage(); //newPage is the name of the newPage.xaml file
this.Content = mynewPage;
}
This is working with me.
Like AnthonyWJones said you need to use the navigation framework.
First you'll need to add a reference to System.Windows.Controls.Navigation in your project and refernce it in you MainPage.xaml
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Then you'll need a frame within where you'll switch different XAML pages. Something like this:
<navigation:Frame x:Name="navFrame" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Source=”/Views/First.xaml” />
Now somewhere in MainPage.xaml you could have a Button with a tag
<Button Click="Button_Click" Tag="/Views/Second.xaml" Content="Second" />
and in the Button_Click eventhandler you could switch out the content showed in navFrame.
private void Button_Click(object sender, RoutedEventArgs e)
{
Button theButton = sender as Button;
string url = theButton.Tag.ToString();
this.navFrame.Navigate(new Uri(url, UriKind.Relative));
}
A cool thing to note is that by using NavigationFramework the browser back and forward buttons work perfectly and the URL in the addressbar updates depending on the XAML page you are currently on :)
Looks like you've started off on the wrong foot. This sort of thing is catered for using the Navigation application template. You should start a new project and select "Silverlight Navigation Application".
Once loaded just run it to see what the basic shell looks like. Then take a look at how MainPage is structured and say the Home view. What you will need to do is create new views based on the navigation Page type and then add them to MainPage.xaml.
The simple one to solve this problem, you can look at this website : http://blogs.microsoft.co.il/blogs/eladkatz/archive/2011/01/25/adapting-silverlight-navigation-to-mvvm.aspx .
I had this problem to earlier. But after I read this tutorial, I can easily navigating to another view with MVVM. Hope this can help you all solve the problem.Thx
private void formcombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (ComboBoxItem child in formcombobox.Items)
{
if (child.Name != null && child.IsSelected == true)
{
string url = new System.Uri("/DWRWefForm;component/Pages/"
+ child.Name + ".xaml", System.UriKind.Relative).ToString();
this.navframe.Navigate(new Uri(url, UriKind.Relative));
}
}
}
Try this:
private void imageEdit1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
newPage mynewPage = new newPage(); //newPage is the name of the newPage.xaml file
this.Content = mynewPage;
}
It's working for me. :)

Resources