LeftClick Context Menu behavior in WPF or Silverlight

Sometimes you just have to be different and want the context menu to appear when you left click as well.

Nothing is wrong with being different, so here is a behavior to do just than.

I assume you know what a behavior is and how to implement it, right? If not, your at the wrong place.

Note: I use a button for this, easier to capture a nice Click.

Behavior code class:

using System;
using System.Windows;
using System.Windows.Controls;

namespace Seekford.Behaviors{
    public static  class LeftClickContextBehavior
    {

        private static void OnHandleEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ele = d as Button;
            if (ele != null)
            {
                ele.Click -= OnClick;               
                if (e.NewValue != null && ((bool)e.NewValue))
                {
                    ele.Click += OnClick;                   
                }
            }
        }

        public static readonly DependencyProperty EnabledProperty
            = DependencyProperty.RegisterAttached("Enabled", typeof(bool), typeof(LeftClickContextBehavior),
                                                  new FrameworkPropertyMetadata(false,
                                                                                new PropertyChangedCallback(
                                                                                    OnHandleEnabledChanged)));
        public static bool GetEnabled(DependencyObject dependencyObj)
        {
            if (dependencyObj == null)
                throw new ArgumentNullException("dependencyObj");

            return (bool)dependencyObj.GetValue(EnabledProperty);
        }

        public static void SetEnabled(DependencyObject dependencyObj, bool value)
        {
            if (dependencyObj == null)
                throw new ArgumentNullException("dependencyObj");

            dependencyObj.SetValue(EnabledProperty, value);
        }

        private static void OnClick(object sender, RoutedEventArgs  e)
        {
            var ele = sender as Button;
            var originalSender = e.OriginalSource as DependencyObject;
            var logicalSender = e.OriginalSource as FrameworkElement;
            var logicalSource = e.Source as FrameworkElement;

            if (ele == null || originalSender == null || sender == null || logicalSource == null || logicalSender == null)
                return;

            if (logicalSource.DataContext != logicalSender.DataContext)
                return;

            var dependencyObject = sender as DependencyObject;
            if (dependencyObject == null)
                return;

            if (ele.ContextMenu != null)
            {
                ele.ContextMenu.PlacementTarget = ele;
                ele.ContextMenu.IsOpen = true;
            }
        }

    }
}


Sample implementation

<UserControl x:Class="Seekford.View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
             xmlns:Behaviors="clr-namespace:Seekford.Behaviors"
>


<Button Behaviors:LeftClickContextBehavior.Enabled="True">
     <Button.ContextMenu >
      <ContextMenu ItemsSource="{Binding MenuStuff}" >
           <ContextMenu.ItemTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Name}"/>
           </DataTemplate>
        </ContextMenu.ItemTemplate>
      </ContextMenu>
    </Button.ContextMenu>
    <Button.Template>
        <ControlTemplate>
          <StackPanel>
               <Textblock Text=”test”/>
         </StackPanel>
         </ControlTemplate>
    </Button.Template>
</Button >


Happy coding!

 

WPF LinkButton – Easy as pie

Where in the world is the LinkButton? I am sure its there somewhere but I just didn’t find it. So, what’s a guy to do? Get some style, that’s what.

WPF makes restyling controls incredibly easy. So much, I switched gears from a WinForms project to use WPF to make the interface look great without resorting to a million third party controls.

I assume you are familiar with WPF and know how to apply a style to a control. Well, apply this to a Button. Just paste the code below in your UserControl.Resources or Window.Resources section and then apply the Style={StaticResource LinkButton} to the button.

Note: I hate underlined links. You can add the underline by changing the TextFormatter on the TextBlock wrapping the content presenter.

 

  <Style x:Key="LinkButton" TargetType="Button">

            <Setter Property="Template">

                <Setter.Value>

                    <ControlTemplate TargetType="Button">

                        <TextBlock>

                    <ContentPresenter />

                        </TextBlock>

                    </ControlTemplate>

                </Setter.Value>

            </Setter>

            <Setter Property="Foreground" Value="Blue" />

            <Setter Property="Cursor" Value="Hand" />

            <Style.Triggers>

                <Trigger Property="IsMouseOver" Value="true">

                    <Setter Property="Foreground" Value="Red" />

                </Trigger>

            </Style.Triggers>

        </Style>

Happy Coding!

Bind to an ICommand on ViewModel with objects in an ItemsControl in WPF

I spent a few minutes beating my head on binding a command to a button that I had in an ItemsControl. Mainly, was creating a list of “link” buttons and wanted them to pass their binding argument to my command on the main view model.

Well, since the DataContext to the content is not the main view model but the individual data item that is in the ItemSource for the ItemsControl, you have to get creative.

Enter the RelativeSource binding. This great tool allows you to search up in the visual hierarchy and grab different data contexts. Simply put, I use the FindAncestor to search for my main UserControl instance, and then go off its DataContext to grab the command. Nice and easy.

Below is the code. Should be easy to follow:

<Window x:Class="SSI.Views.SelectorView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              mc:Ignorable="d"
             xmlns:views="clr-namespace:SSI.I8N.LanguagePackEditor.Views"
        Title="SSI">
                <ItemsControl Margin="0" ItemsSource="{Binding Folders}">
<ItemsControl.ItemTemplate>
<DataTemplate>
 <Button Content="{Binding}" Command="{Binding DataContext.FolderCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type views:SelectorView}}}" CommandParameter="{Binding}"/>
                </DataTemplate>
           </ItemsControl.ItemTemplate>
</ItemsControl></Window>

Happy coding!

WPF not compiling: program does not contain a static ‘Main’ method

I decided to create a new WPF application. I started the project out intending to use WinForms, but then I hit a limitation(pain) that prompted me to switch to WPF. A list of link buttons, easily accomplished in WPF, but annoying in WinForms.

So, I created an App.xaml, deleted my Programs.cs and Main and went compile.

Boom! Error, no Main method. hmmmm… I stared at another one of my WPF projects and didn’t see the magic missing setting. Finally, it dawned on. The compile options for the App.xaml.

Set the compile option to Application Definition and away you go. So simple, yet so non-obvious.

image

Happy Coding!

Inaugural Wine and Dine Half Marathon – Finished

My wife and I ran the half marathon at Disney this Saturday night. It was our first endurance event, and let me tell you it was amazing and hard.

The race began at 10:00 pm with 11,500 of our closest friends. That is a lot of people corralled together. It took 13 minutes to get from where we were in Corral D to the start line when the gun/fireworks were fired off.  A bunch of slow waddling, kind of like the delay at a traffic light.

The race took us through the streets from the ESPN World of Sport over to the Animal Kingdom park. We ran through part of the park and back out around the parking lot and back through to the main street again. From there we double backed and then went down and off ramp and ran through the back of MGM.

The MGM part was really cool, went through the and saw the back of Tower of Terror and then through the Stunt Show and then got to run through the Christmas Lights on the street scene. From there, we then ran out of the park and past the lagoon over past the Yacht and Beach club to the Finish Line at the World Gate( back gate) of Epcot.

Overall, the experience was amazing. Each Mile has a big gateway that said the mile # and was sponsored by a country. There were DJ’s and characters all along the run, and even a live band playing a few good songs.

I thought I would be upset for not bringing my headphones, but there was music and entertainment and “cheer squads” almost every step of the way.

I injured myself at about mile 8 or 9, hard to remember. My knee went out pretty bad, but I forced myself to suck up the pain and continue. The last two miles was a slow walk with me hobbling, but pain is temporary. My wife provided extra support by walking with me, and we finished together.

We did run through every mile gate though. The last few hurt pretty bad, but it had to be done.

I am just proud I finished and am looking forward to the next run in January. This time I will train much harder, to not only just finish, but finish with a good time.

I have my  medal and some great new confidence. I now know I can conquer 13.1 miles.  To all you 26.2 mile marathoners, I think you guys are nuts.

-Brian

PS:

The race I ran: Wine and Dine Marathon

The race in January: Marathon Weekend