Archive for category XAML

Adding a glow in Silverlight with the DropShadowEffects class

I wanted to have a mouse-over effect for my Path – I mean, who doesn’t? Ladies love guys that can dynamically add Silverlight glow effects as much as they like guys that can use the ternary operator. So I’m going to tell you how to improve your love life.

First, the XAML. Notice the use of MouseEnter and MouseLeave events on my Path object:

    <Grid x:Name=”LayoutRoot” Background=”White”>
        <Path x:Name=”ScottPath” Stroke=”Black” Data=”M 20,100 C 10,300 300,-200 300,100″ MouseEnter=”Path_MouseEnter” MouseLeave=”Path_MouseLeave” />
    </Grid>

Oh yeah, that’s right – I’m using a Bezier curve. This keeps getting better.

Now into the code behind we go. Before you enter the wonderful world of DropShadowEffects, you’ll need to add a reference to the right library:

using System.Windows.Media.Effects;

And away we go:

        private void Path_MouseEnter(object sender, MouseEventArgs e)
        {
            DropShadowEffect dropShadow = new DropShadowEffect();
            dropShadow.BlurRadius = 10;
            dropShadow.Color = Colors.Purple;
            dropShadow.Direction = 0;
            dropShadow.Opacity = 1.0;
            dropShadow.ShadowDepth = 0;

            ((Path)sender).Effect = dropShadow;
        }

        private void Path_MouseLeave(object sender, MouseEventArgs e)
        {
            ((Path)sender).Effect = null;
        }

What I have going on is that when the mouse hovers over the Path object, I create an instance of the magical DropShadowEffect class, set all the variables that make me feel happy and wonderful, and add the DropShadowEffect  to the Effect property of the Path object. And when the mouse leaves the path, I set the Path.Effect to null to get rid of the effect.

No worries, no fuss, just an awesome purple glow on your line.

Advertisements

Leave a comment

Creating a Silverlight – WPF Button in code behind

In WPF or Silverlight, to add a Button from code behind insted of in XAML, first make sure the content control has a Children property. For example, I could not add to the SearchPanel Border control in the code below because it lacks such a property.

<Border Name="SearchPanel" CornerRadius="10" BorderBrush="Black" BorderThickness="1">
     <StackPanel Name="SearchStackPanel" />
</Border>

Why’s that? Border inherits from System.Windows.FrameworkElement, which lacks, you guessed it, the Children property. However, StackPanel inherits from System.Windows.Controls.Panel, which does have it.

Now, to actually add the button:

Button RandomButton = new Button();
RandomButton.Name = "RandomButton";
RandomButton.Content = "Random Location";
RandomButton.Click += new RoutedEventHandler(RandomButton_Click);
RandomButton.Height = 25.0;
RandomButton.Width = 100.0;
SearchStackPanel.Children.Add(RandomButton);
private void Random_Click(object sender, RoutedEventArgs e)
{
     // Stuff
}

Leave a comment

Shadow and glow effects in Silverlight

I was looking around for how to create a shadow effect for a Border object in Silverlight. I found Pete Brown’s blog, which made my job very easy. Since I had dark backgrounds, I wanted a white shadow. Simply adding a DropShadowEffect to the Border did the trick:

 <Border>
            <Border.Effect>
               <DropShadowEffect BlurRadius="10" Color="White"  Opacity="0.75" Direction="300" />
           </Border.Effect>
</Border>

 If you are looking for a glow effect, where the entire border is surrounding by the shadow effect inside of just having it in one area, set the Direction property to 0:

 <DropShadowEffect x:Key="BorderShadowStyle" BlurRadius="30" Color="White" Opacity="1" Direction="0" ShadowDepth="0" />

 But what if you have lots of Borders that you want to add this effect to? Then you put it into the App.xaml page, of course:

 <Application xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
             xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
            x:Class="Testing.App">
    <Application.Resources>
        <DropShadowEffect x:Key="BorderShadowStyle" BlurRadius="10" Color="White"  Opacity="0.75" Direction="300" />
    </Application.Resources>
</Application>

 Then, when creating new Border objects, you simply set the Effect property to the name you defined in the App.xaml file.

 <Border Effect="{StaticResource BorderShadowStyle}"></Border>

 But watch the performance! I added a glow effect to a dozen different Borders with no problems, but added it to one more and the system slowed down significantly when displaying that particular Border and the controls within. Removing that particular glow effect brought the performance back to normal.

References:

  http://10rem.net/blog/2009/03/18/silverlight-3-%E2%80%93-drop-shadows-and-glows-with-pixel-shaders

 http://msdn.microsoft.com/en-us/library/system.windows.media.effects.dropshadoweffect(VS.95).aspx

1 Comment

XAML error – System.Windows.Baml2006.TypeConverterMarkupExtension

Notice, if you will, this itty bitty block of code:

<ListBox Name="FilesList" ItemsSource="{Binding FileList}" Width="100%">
 <ListBox.ItemTemplate>
  <DataTemplate>
   <TextBlock Text="{Binding}" />
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

While attempting to databind a custom collection class to a ListBox, I encountered an oddly named exception:

XamlParseException occurred
Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.

What the heck is Baml2006?

Anyway, here is the offending line:

<ListBox Name="FilesList" ItemsSource="{Binding FileList}" Width="100%">

Guess which part is the problem? The ‘Width=”100%”‘ part. When I changed it to read ‘Width=”350″‘, the error went away. No worries, but a more helpful error message would have been nice.

I’ve also received the “BAML” error where there are other invalid characters in a property value. So don’t put those invalid characters in property fields, kids – that’s bad.

1 Comment

Creating a flashing taskbar icon using FlashWindow with XAML

Looking to notify your users when an application wants its needs met? A sure fire way is to have its taskbar icon flash. Here’s how.

First, import those namespaces, people:

using System.Windows.Interop;
 using System.Runtime.InteropServices;

Next, declare the Windows API FlashWindow method.

[DllImport("user32")] public static extern int FlashWindow(IntPtr hwnd, bool bInvert);

Notice the first parameter is a IntPtr, NOT an int, like I found at one of the websites I visited trying to get this working. An int will get you nowhere. IntPtr is your friend.

Now create a WindowInteropHelper by passing the WPF Window object that you are calling the code from. Pass the window’s Handle property to the FlashWindow method, along with a value of “true”, to tell it that you want the awesome flashing taskbar effect.

WindowInteropHelper wih = new WindowInteropHelper(ThisWindow); 
FlashWindow(wih.Handle, true);

There we go, a simple way to alert users when your application is done or has updated information.

Leave a comment

Silverlight: Getting the parent ListBox SelectedItem property of a child Button

Thanks to Anthony on StackOverflow for solving this problem for me.

I had the following XAML code, having removed the styling and formatting tags:

<ListBox Name=”ManageImageList”>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Image Name=”ManageImageThumbnail” Source=”{Binding ImageName}” />
                <StackPanel Orientation=”Vertical” >
                    <TextBlock Name=”ManageImageUrl” Text=”{Binding ImageName}” />
                    <TextBlock Name=”ManageImageComment” Text=”{Binding Comment}” />
                </StackPanel>
                <Button Name=”ManageImageDelete” Click=”ManageImageDelete_Click” Content=”X” />
           </StackPanel>
        </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

The ListBox was bound to an ObservableCollection. I wanted to give focus to the parent ListBox item when the button is clicked, making it the SelectedItem of the ListBox. But I didn’t know how to do that.

Anthony provided this answer:

private void ManageImageDelete_Click(object sender, RoutedEventArgs e)
{
     ManageImageList.SelectedItem = ((Button)sender).DataContext;
}

Exactly what I needed, and it worked perfectly.

2 Comments

Jumping to specific record in a Silverlight ComboBox

I had a ComboBox that contained a list of U.S. states. I wanted this ComboBox to have functionality that would enable a user to enter a letter or two and have the correct item highlighted. This simple change was very easy to make.

First, a bit of XAML to define my ComboBox:

<ComboBox Name=”State” KeyDown=”State_KeyDown” Height=”25″ Grid.Column=”1″ Grid.Row=”2″ />

Now for the KeyDown event.

        private void State_KeyDown(object sender, KeyEventArgs e)
        {
            foreach (string Item in State.Items)
            {
                if (Item.StartsWith(e.Key.ToString()))
                {
                    State.SelectedItem = Item;
                    break;  // Find after the first match
                }
            }
        }

If you are just interested highlighting the element based on the first character, this little snippet will work:

        string DDLValue = string.Empty;

        private void State_KeyDown(object sender, KeyEventArgs e)
        {
            DDLValue += e.Key.ToString();

            foreach (string Item in State.Items)
            {
                if (Item.StartsWith(DDLValue))
                {
                    State.SelectedItem = Item;
                    break;  // Find after the first match
                }
            }
        }

The string can be cleared out at another time. I did it when the Close button is clicked on the parent window.

The above works, but it will not work after the first time the text is entered – the value is persisted. To clear the string of previous values, so the user could type in a new state the next time they entered the window, or even if they tabbed off the ComboBox, I added a LostFocus event to the State ComboBox definition, and added this in the code behind:

private void FollowSearchState_LostFocus(object sender, RoutedEventArgs e)
{
            DDLValue = string.Empty;
}


So, the full working code is this:

XAML:

<ComboBox Name="State" KeyDown="State_KeyDown" LostFocus="State_LostFocus" />

C#:

private void FollowSearchState_KeyDown(object sender, KeyEventArgs e)
{
            if (DDLValue.Length <= 2)
                DDLValue += e.Key.ToString();
            foreach (string Item in FollowSearchState.Items)
            {
                if (Item.StartsWith(DDLValue))
                {
                    FollowSearchState.SelectedItem = Item;
                    break;  // Find after the first match
                }
            }
            FollowSearchState.Focus();
}
private void FollowSearchState_LostFocus(object sender, RoutedEventArgs e)
{
            DDLValue = string.Empty;
}

Leave a comment