Silverlight ComboBox Attached Behavior

Posted by Mark Cooper on Stack Overflow See other posts from Stack Overflow or by Mark Cooper
Published on 2010-03-15T10:59:12Z Indexed on 2010/03/15 13:19 UTC
Read the original article Hit count: 680

I am trying to create an attached behavior that can be applied to a Silverlight ComboBox.

My behavior is this:

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

namespace AttachedBehaviours
{
    public class ConfirmChangeBehaviour 
    {

        public static bool GetConfirmChange(Selector cmb)
        {
            return (bool)cmb.GetValue(ConfirmChangeProperty);
        }

        public static void SetConfirmChange(Selector cmb, bool value)
        {
            cmb.SetValue(ConfirmChangeProperty, value);
        }


        public static readonly DependencyProperty ConfirmChangeProperty =
            DependencyProperty.RegisterAttached("ConfirmChange", typeof(bool), typeof(Selector), new PropertyMetadata(true, ConfirmChangeChanged));
        public static void ConfirmChangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
        {
            Selector instance = d as Selector;

            if (args.NewValue is bool == false)
                return;

            if ((bool)args.NewValue)
                instance.SelectionChanged += OnSelectorSelectionChanged;
            else
                instance.SelectionChanged -= OnSelectorSelectionChanged;

        }

        static void OnSelectorSelectionChanged(object sender, RoutedEventArgs e)
        {
            Selector item = e.OriginalSource as Selector;

            MessageBox.Show("Unsaved changes. Are you sure you want to change teams?");    

        }

    }

}

This is used in XAML as this:

<UserControl x:Class="AttachedBehaviours.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"
             xmlns:this="clr-namespace:AttachedBehaviours"
             mc:Ignorable="d">
    <Grid x:Name="LayoutRoot">
        <StackPanel>
            <ComboBox ItemsSource="{Binding Teams}" 
                      this:ConfirmChangeBehaviour.ConfirmChange="true" >
            </ComboBox>
        </StackPanel>
    </Grid>
</UserControl>

I am getting an error:

Unknown attribute ConfirmChangeBehaviour.ConfirmChange on element ComboBox. [Line: 13 Position: 65]

Intellisense is picking up the behavior, why is this failing at runtime?

Thanks, Mark

EDIT: Register() changed to RegisterAttached(). Same error appears.

© Stack Overflow or respective owner

Related posts about silverlight-3.0

Related posts about Silverlight