Sunday, April 27, 2014
I love it! This is the best WP release to date. There is one problem I’ve run into that has been driving me nuts for the past few days. I finally found a fix for it, so I thought I would share it.
A lot of people are experiencing this issue. After upgrading, I was getting an error every time I tried to surf the web on my phone. The strange thing was that I was still connected to the internet. All my apps got their data (email, facebook, etc), but whenever I used the browser, I would get an error.
After a lot of searching, I found the solution here:
http://forums.wpcentral.com/windows-phone-8-1-preview-developers/275515-2.htm
The basic steps are:
1)Go to settings> Access Point
2)Write down all the settings from your current access point (tap and hold acces point and choose view to see settings)
3)Go back and create a new access point
4)Copy all the original access point settings to your new access point, but leave the proxy and port fields blank
5)Set your new access point as the active access point.
6)Start surfing the web!
I just got this working on my phone, and so far, so good. Only time will tell if the solution sticks, but from what I’m seeing out there… it works.
I hope this helps!
Tuesday, March 11, 2014
Windows Phone–Removing Duplicate Songs and/or Albums
Time for another post that has nothing to do with development…
If you own a Windows Phone, you have probably seen duplicate songs or albums in your music library. This can be a very frustrating bug to deal with and it is difficult to fix. It would be nice if you could simple select a track or album and delete it right from your phone. Unfortunately, Microsoft does not allow us to do that. It would even be great if connecting the phone to your computer and deleting it files in the file browser or via the Windows Phone app would take care of it for you. Well… no. That doesn’t always work. After struggling with this for a little while, I found a solution that worked for me. Hopefully it works for you too if you are in the same boat. Here is what I did to remove the duplicate songs.
-Connect the phone to your computer with the usb cable and open it up in Windows Explorer.
-Locate the Music folder.
-Select View > Show Hidden Files (from the toolbar or ribbon control depending on what os you are running)
-Once you are seeing the hidden files, you should see an Artists folder that contains a file for each artist in your collection. Find the artist that has the duplicate files and erase that file.
-Navigate to that artist’s corresponding music files directory on your phone and delete those files.
-Copy the music files from your music library on your pc back onto your phone. This should re-generate that file you previously deleted under the hidden Artists directory. This is the file that tells your phone what files to display.
That should do it. You can now disconnect your phone and see no more duplicate files (or at least that worked for me).
Good luck!
Friday, March 7, 2014
OutOfRangeInput Error in Azure
I’m fairly new to Azure programming. Maybe this is obvious to everyone out there, but it wasn’t obvious to me, so I figured I’d record it on my blog for all you newbies out there like me.
I have been working on a simple application that stores data in a table in Azure. Because I am new to Azure table storage, I followed a few online tutorials to get started. Here is one of the ones I read.
http://www.windowsazure.com/en-us/documentation/articles/storage-dotnet-how-to-use-table-storage-20/
I made a few basic changes to my code rather than copying it word for word. When I tried to run my app, I kept getting a
StorageException - The remote server returned an error: (400) Bad Request.
every time I tried to insert a new row in the table. The samples were so simple and I thought I followed them closely. I spent a couple of hours trying to figure out what was going on, and I finally stumbled upon the answer. This took WAY TOO MUCH time to figure out, so I hope this helps you out in your development.
So here is the deal…
When I created my entity that I was going to insert, I had a DateTime.Now.ToString as part of the row key in the entity. It turns out you can’t use that in partition keys or row keys. When you are running on Azure, the format for the date is “YYYY/MM/DD”. The ‘/’ character is not permitted in row keys or partition keys.
Once I removed that, everything worked smoothly.
It was a simple error, but like I said before, it took way too long to figure out.
Happy Coding Folks!
Wednesday, July 10, 2013
WPF–SoundPlayer Bug
Here is an interesting one. I was using the SoundPlayerAction in WPF to plan a small .wav file when a view was loaded, and I noticed that sometimes I would get a very strange screeching sound while the audio was playing. This did not happen all the time, but it happened enough that it needed to be fixed. The bug was more apparent on certain machines than others. After some digging around, I found out it had to do with the Garbage Collector of all things. Essentially, the GC automatically decides to start moving the bytes used in the sound file before it’s done playing the file. This causes the annoying screeching sound. So how did I fix this issue? The solution that worked for me was to simply change the build action on my sound files from resource to content. I then had to change all my references to my audio files to use the correct format (from pack://application to pack://siteoforigin) and that took care of the issue. This bug only presents itself when trying to play audio from embedded resources. If playing directly from a file, you should not have the same problem.
Here are the links I found explaining more about the bug and how to get around it.
http://www.codeproject.com/Articles/13909/SoundPlayer-bug-Calling-unmanaged-APIs
Happy Screech-Free Coding!
Wednesday, June 5, 2013
Keeping the Selection Color in a WPF Listbox When it Loses Focus
There are a lot of blog posts out there telling you to change the the ControlBrush resource of a listbox in order to maintain the selection color when the listbox item loses focus. This does not work.
If you want to set the color of the background when an item is selected, you need to change the HighlightBrush. If you want that color to persist even after the item loses focus, you need to change the InactiveSelectionHighlightBrush.
Hope this helps. Happy Coding!
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Black"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
Color="Black"/>
</ListBox.Resources>
Wednesday, May 29, 2013
WPF Effects and Blurry Fonts
I recently ran into a very strange bug that took me a while to figure out. I noticed that several buttons in my UI had blurry text. I thought I may have mistakenly changed the opacity or had some semi-transparent gradient overlaying the font that made it look so blurry. That did not turn out to be the case. After digging around a bit I found out what was causing the problem. It turns out that the problem was in my control template. I defined the button to have a border which contains a label inside it’s content. I applied the drop shadow to the outer border and was surprised to find that applying that effect to the border caused the contents of the border to become blurry. After a little research I found that using an effect causes the elements and all the sub-elements inside the control to be rendered into a Bitmap. When this happens, WPF cannot use ClearType rendering to display the text. This causes it to look blurrier than if there is not effect applied.
Here is what my buttons looked like with the drop shadow
And here is the same button without the drop shadow
To get around this bug simply place the text outside of the control that you will be applying the effect to.
<Border>
<Border.Effect>
…
</Border.Effect>
<TextBlock Text=”Blurry Text”/>
</Border>
//Change the code above to this.
<Grid>
<Border>
<Border.Effect>
…
</Border.Effect>
</Border>
<TextBlock Text=”Clear Text”/>
</Grid>
If you run into this issue, just change your code like what I did above and you should have clear text on your buttons even if you are using effects.
Happy Coding.
Tuesday, April 16, 2013
Using Animated Gifs with WPF
Ever wish you could use an animated gif in your WPF application? Well, here is an easy way to do so. Simply use the WpfAnimatedGif Nuget package available on codeplex. With that library, you can easily display animated GIFs in your application via XAML or code.
Here is what the markup looks like…
…
xmlns:a=http://wpfanimatedgif.codeplex.com
…<Image a:ImageBehavior.AnimatedSource="Images/myImage.gif"/>
Head over to http://wpfanimatedgif.codeplex.com/ for more info.
Happy Coding!
Monday, April 15, 2013
Iterate through Dictionary Entries in Merged Dictionaries
Just a quick post to show you how to iterate through resource dictionary entries when using merged resource dictionaries. It is fairly straight forward. I came across someone wondering how to do this, so I thought I’d share. You simply iterate through all your merged dictionaries and then iterate through each dictionary entry in the dictionary. Here is the code below.
foreach (ResourceDictionary dict in Application.Current.Resources.MergedDictionaries)
{
foreach (DictionaryEntry entry in dict)
{
//Process entry
}
}
Hope this helps.
Monday, April 1, 2013
MessageDialog - Windows Store App MessageBox.Show Equivalent.
If you are new to Windows Store app development, you may be wondering how to show a simple dialog. It used to be so easy. You simply called MessageBox.Show() and you had a dialog. Well, in Windows Store Applications in Windows 8, it is a bit different but just as easy.
Try this code instead of MessageBox.Show to get the following dialog…
var messageDialog = new Windows.UI.Popups.MessageDialog("Message Text.","Message Header");
messageDialog.ShowAsync();
Happy Windows Store App Coding!
Sunday, March 31, 2013
Windows Store App… How to set focus on a textbox
A common task in UI development is setting the focus on a textbox when navigating to a particular screen. When doing this on a Windows 8 application, a lot of developers try to do this inside the OnNavigatedTo event handler. This does not work. To set the focus on a textbox when the page is hit, call the focus method on the particular textbox inside the loaded event handler… That should do it.
<common:LayoutAwarePage
x:Name="pageRoot"
…
Loaded="pageRoot_Loaded_1">
private void pageRoot_Loaded_1(object sender, RoutedEventArgs e)
{
this.txtName.Focus(FocusState.Programmatic);
}
Hope this helps. Happy Coding!
Friday, March 29, 2013
ChangeAwareContentControl–How to know when the content changes in a ContentControl
I am working on an application where I have a ContentControl, and I need to know when the content changes. My initial thought was to add an event handler for the ContentChanged event. I came to find out that the ContentControl does not fire a ContentChanged event.
My solution was to create a control derived from content control that fires that particular event. It is working quite nicely, so I thought I would share. I hope it helps you out. It’s a small amount of code, but it does the trick.
public class ChangeAwareContentControl : ContentControl
{
static ChangeAwareContentControl()
{
ContentProperty.OverrideMetadata(typeof(ChangeAwareContentControl),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnContentChanged)));
}
private static void OnContentChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
ChangeAwareContentControl mcc = d as ChangeAwareContentControl;
if (mcc.ContentChanged != null)
{
DependencyPropertyChangedEventArgs args
= new DependencyPropertyChangedEventArgs(
ContentProperty, e.OldValue, e.NewValue);
mcc.ContentChanged(mcc, args);
}
}
public event DependencyPropertyChangedEventHandler ContentChanged;
}
Here is how you use it in xaml.
<controls:ChangeAwareContentControl ContentChanged="ContenChangedHandler"/>
Thursday, March 28, 2013
BitmapImage.BeginInit()
A very common error new UI developers make is trying to create new BitmapImages without properly initializing them.
All property changes made to a BitmapImage must be made between the BeginInit() and EndInit() calls. Every property change made after the EndInit() call is ignored.
Here is a small code snippet on how to properly create a new bitmap image and set that as the source of an Image object.
// Define a BitmapImage.
Image myImage = new Image();
BitmapImage bi = new BitmapImage();
// Begin initialization.
bi.BeginInit();
// Set BitmapImage properties. (CacheOption,CreateOptions… etc.)
// End initialization.
bi.EndInit();
myImage.Source = bi;
Wednesday, February 13, 2013
How to Scroll to Selected Datagrid Item
If you programmatically select an item on a WPF datagrid, you may need to scroll to make sure that item is visible. One line of code will take care of that for you.
myGrid.ScrollIntoView(myGrid.SelectedItem);
That should do it.
Happy Coding!
Tuesday, February 12, 2013
WPF- What’s Going On With My DataGrid Checkbox?
This is a very common mistake and I found myself committing it recently.
Sometimes you will find yourself wanting to create a datagrid column that contains a checkbox. The simplest way of doing this is by defining a DataGridCheckBoxColumn.
<DataGridCheckBoxColumn Binding="{Binding IsSelected}"/>
There are some situations when you might want to use a DataGridTemplateColumn instead because you want to tweak some visuals or add other controls inside the cell.
<DataGridTemplateColumn Width="30">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
When people do this, they sometimes find that the bindings don’t work properly. If they click on the checkbox, they notice that the property they are binding to (in this case IsSelected) does not update until you click somewhere else in the cell. Some people even miss this and just think the binding does not work at all. I ran across a case where a developer had two datagrid columns side by side, one was the DataGridCheckBoxColumn and the other one was a DataGridTemplateColumn like the ones above. The developer was convinced that something was going on because the binding was working for one and not the other.
If you run into this, don’t worry. The binding is working. It’s just not updating the bound property at the correct time. To fix this, simply make the following tweak to the binding statement. This should now cause the property to change immediately once the checkbox is checked (once the IsChecked property changes).
<DataGridTemplateColumn Width="30">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
That’s it. Hope this helps.
Happy Coding!
Thursday, February 7, 2013
WPF Tooltip
<Button Content="Button" ToolTip="This is a tooltip"/>
There are various properties that can be adjusted to tweak the behavior of the tooltip. This is done via the TooltipService attached property.
<Button Content="Button" ToolTip="This is a tooltip" ToolTipService.HasDropShadow="False"> </Button>
The properties that can be tweaked on the TooltipService are:
| BetweenShowDelay | This value specifies how much time (in milliseconds) the user has to move from the control that is displaying the tooltip to another one without having to wait for it’s InitialShowDelay. Essentially, if I set this value to X, once I see the tooltip on my control, I have X milliseconds to hover over another control that has a tooltip and that other tooltip will show up immediately. |
| HasDropShadow | Specifies if the tooltip has a dropshadow. |
| HorizontalOffset | Offset from the left of the area that is specifies for the tooltip. |
| InitialShowDelay | How long it takes for the tooltip to open (in milliseconds). |
| IsEnabled | Determines whether the tooltip gets displayed. |
| IsOpen | Gets whether the tooltip is open. |
| Placement | Sets the orientation of the tooltip when it opens |
| PlacementRectangle | Gets or sets the rectangle area in which the tooltip is displayed |
| ShowDuration | Specifies the amount of time the tooltip is displayed |
| ShowOnDisabled | Specifies if the tooltip is displayed when the parent object is disabled |
| ToolTip | Gets or sets the content of the tooltip |
VerticalOffset | Offset from the top of the area that is specifies for the tooltip. |
You can any visual element as the content of a tooltip by defining in a nested element rather than an attribute.
<Button Content="Button"> <ToolTipService.ToolTip> <Rectangle Fill="Red" Height="20" Width="20"/> </ToolTipService.ToolTip> </Button>
Happy Tooltiping!
Tuesday, February 5, 2013
The Basics: Intro to Windows Presentation Foundation
The Links First, here are a few useful links to get you started
http://www.microsoft.com/expression/
download Microsoft Expression Blend
http://www.microsoft.com/visualstudio/eng/products/visual-studio-overview
go to express products to download the free version of Visual Studio
This is by far the Best book for learning WPF. I highly recommend it
Introduction Now that I've used the term WPF several times, I should probably give a formal definition for it. As seen in the title of this blog post, WPF stands for Windows Presentation Foundation. So why use WPF when there are other options like Windows Forms out there? While there are many opinions out there, I believe the biggest benefit to using WPF is that it provides a clear separation between the application behavior and the user interface. Rather than defining the user interface in code like VB or C#, WPF introduces xaml (eXtensible Application Markup Language). This xml markup is used to define the user interface. When an application is built, the compiler reads the xaml (pronounced zammel) markup and generates the appropriate objects to construct the user interface.
Everything you can do in xaml you can do in code. You can create a WPF application without writing a single line of xaml, but that is not common. Declaring your user interface in xaml provides a cleaner separation between the look of the application and the behavior of the application. It also allows you to use the design tools (like Expression Blend) available for creating complex user interfaces. Also, xaml is much easier to read and a lot shorter than code.
C# / Xaml Comparison
The following xaml and c# code both produce the same result – the following interface.
xaml
<Grid> <StackPanel> <Label Content="My First WPF App"/> <Button Content="Hello World"/> <TextBox/> </StackPanel> </Grid>
C#
Grid g = new Grid(); StackPanel s = new StackPanel(); Label l = new Label(); l.Content = "My First WPF App"; Button b = new Button(); b.Content = "Hello World"; TextBox t = new TextBox(); //populate stack panel s.Children.Add(l); s.Children.Add(b); s.Children.Add(t); //add stackpanel to grid g.Children.Add(s); //set application content this.Content = g;
From this small example you can clearly see that the C# code is much longer and more difficult to read than the equivalent xaml markup.
Xaml Basics
To initialize an object simply create a new xml element.
<StackPanel/>
<Button/>
<Label/>
<TextBlock/>
<TextBox/>
<ListBox/>
. . .
There are two ways of adding properties to elements:
1)Inline
<StackPanel Orientation="Horizontal" Margin="2"/>
<Button Content="Click Me" Height="50" Width="100"/>
<Label Content="Hi"/>
<TextBox Text="Enter text here"/>
<ListBox Height="300"/>
or
2) As nested elements. This allows building more complex elements.
<Button Height="50" Width="100"> <StackPanel Orientation="Horizontal"> <Label Content="Click"/> <Image Source="click_here.png"/> </StackPanel> </Button>
The Visual Tree
WPF introduces the notion of a visual tree and a logical tree. It is important to understand the difference between the two.
When building a user interface, one can talk about the different elements that make up the interface. That is what is referred to as the logical tree.
<Grid> <Button/> </Grid>
The logical tree for this code is represented as
The visual tree refers to the various visual elements that make up a logical element. The logical tree just for the button above is represented as:
This specifies, in great detail, how the button control is visually constructed. WPF gives developers the flexibility to completely redefine visual tree of any given control. This is done via Styles and Templates.
Styles and Templates
Here is where WPF development, in my opinion, really shines. Styles can be used to make reusable chunks of code that define visual properties of specific UI elements or a certain type of element. They are very similar to Cascading Style Sheets in web development. With styles, you can easily define the look for all the buttons within a given application as a single style and apply it globally.style
Below I define 4 styles for Label controls. The first is the default style for all labels within scope. If a label is created within the scope of this style and no style is defined, it will pick up the properties defined by this style. Default styles are created in WPF by simply creating a style without giving it a Key (style identifier).
<Style TargetType="{x:Type Label}"> <Style.Setters> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="FontSize" Value="40"/> </Style.Setters> </Style> <Style TargetType="{x:Type Label}" x:Key="BigBlueStyle"> <Style.Setters> <Setter Property="Foreground" Value="Blue"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="FontSize" Value="40"/> </Style.Setters> </Style> <Style TargetType="{x:Type Label}" x:Key="LittleGreenStyle"> <Style.Setters> <Setter Property="Foreground" Value="Green"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="FontSize" Value="10"/> </Style.Setters> </Style>
The second and third styles both have Keys. In order to use this style, the label must set the Style attribute using the following syntax.
<StackPanel> <Label Content="First Label"/> <Label Content="Second Label" Style="{DynamicResource BigBlueStyle}"/> <Label Content="Third Label" Style="{DynamicResource LittleGreenStyle}"/> <Label Content="Fourth Label" Foreground="Purple"/> </StackPanel>
The product of this code looks like this:
Notice how the fourth label overrides the foreground color to purple.
Templates are a bit different from styles. While styles allow you to set properties, templates allow you to redefine the visual tree of an element. There are two different kinds of templates used in WPF
1)Datatemplate – Used for describing how data should be displayed. This type of template is commonly used in list-based controls like listboxes or comboboxes.
2)ControlTemplate – Used for describing the appearance of a control.
Simple example:
In this example I change the visual tree of the button. This defines the button to be made up of a green grid with an inner stackpanel that has a textblock, a rectangle and a combobox. Note, the user can still interact with any of the elements inside the button like the combobox. This, in my opinion, is the single most powerful feature in WPF. Developers are completely free to redefine visual elements in inumerable ways to meet their needs.
<Button Height="100" Width="200"> <Button.Template> <ControlTemplate> <Grid Background="Green"> <StackPanel VerticalAlignment="Center"> <TextBlock Text="Click Me"/> <Rectangle Fill="Black" Height="30" /> <ComboBox> <ComboBox.Items> <ComboBoxItem Content="Item One"/> <ComboBoxItem Content="Item Two"/> <ComboBoxItem Content="Item Three"/> </ComboBox.Items> </ComboBox> </StackPanel> </Grid> </ControlTemplate> </Button.Template> </Button>
This has only been a quick intro to WPF. I hope it’s been helpful to understand the basics of this technology. Please take a look around this blog to find other articles related to wpf development.
Happy Coding!
Friday, February 1, 2013
C# Basics: Switch Statement
Basic Syntax
If the expression’s value does not match any of the constant values in the switch statement, the control flow is transferred to the statement following the default keyword.switch (expression) { case constant1: statement1; break; case constant2: statement2; break; case constant3: statement3; break; default: default statement; break; }
The switch statement above can also be written with multiple if statements as follows:
if (expression1) { statement1; } else if (expression2) { statement2; } else if (expression3) { statement3; } else { default statement; }
Case fall-through
all case statements within a switch statement must have a reachable endpoint. This is typically the break statement. However, any statement that will jump the execution out of the switch statement will also work. These are statements like return and throw. The only exception to this reachable endpoint rule is when there are no statements between case statements.
In the following example, statement 1 is executed if expression is equal to constant1 or constant2.
switch (expression) { case constant1: case constant2: statement1; break; case constant3: statement3; break; default: default statement; break; }
Thursday, January 3, 2013
How to Detect a Touch Screen (C#)
Just a quick note to show you how to detect a touch screen. This code could be used to hide the application cursor if the application is running on a touch screen device.
I hope it helps.
private bool HasTouchInput()
{
return Tablet.TabletDevices.OfType<TabletDevice>().Any(t => t.Type == TabletDeviceType.Touch);
}
Friday, August 24, 2012
How to Change Application FontFamily at Runtime
private void applyFontFamilySettings()
{
foreach (DictionaryEntry entry in Application.Current.Resources)
{
if (entry.Value is Style)
{
Style originalStyle = (Style)entry.Value;
swapStyles(originalStyle, entry.Key, originalStyle.TargetType);
}
}
}
private void swapStyles(Style s, object styleKey, Type t)
{
Style newStyle = new System.Windows.Style()
{
TargetType = t
};
foreach (Setter st in s.Setters)
{
newStyle.Setters.Add(st);
}
newStyle.Setters.Add(new Setter(FontFamilyProperty, UiSettings.FontFamily));
Application.Current.Resources[styleKey] = newStyle;
}
Thursday, July 5, 2012
How to Create a Custom Stroke in Expression Design
1) First, draw whatever you want to be used as a stroke. In this case, I will drew an ant.
2) Select the paths with the selection tool and go to Object > Stroke > New Stroke Definition
This will open up a new tab that look something like this
3) Select everything with the selection tool and right click. You should see this:
This gives you the option to anchor the image and make repeating. In my case, I want the ants to repeat, so I select that.
4) File > Save
Give your stroke an appropriate name.
That’s it. Now you should be able to use your stroke in your designs.
With this new stroke, I can now make a line of ants following whatever path I want.
I hope this helps! Have fun!