0

I created a behaviour using an attached dependency property to feed a common SetterBaseCollection to different, related styles.

The behaviour just manages the collection on the attached, host property to align it with the static resource in the view. I just wired this to the AP PropertyChangedCallback and this works fine for another behaviour that I have, to populate CommandBindings, but throws when I apply it to style setters.

The error is

System.Windows.Markup.XamlParseException occurred
  _HResult=-2146233087
  _message='Set property 'System.Windows.EventSetter.Event' threw an exception.' Line number '12' and line position '26'.
  HResult=-2146233087
  IsTransient=false
  Message='Set property 'System.Windows.EventSetter.Event' threw an exception.' Line number '12' and line position '26'.
  Source=PresentationFramework
  LineNumber=12
  LinePosition=26
  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
  InnerException: System.ArgumentNullException
       _HResult=-2147467261
       _message=Value cannot be null.
       HResult=-2147467261
       IsTransient=false
       Message=Value cannot be null.
Parameter name: value
       Source=PresentationFramework
       ParamName=value
       StackTrace:
            at System.Windows.EventSetter.set_Event(RoutedEvent value)
       InnerException: 

The Behaviour code is not called before the error occurs so it is something in the xaml.

The View

<Window.Resources>

    <Thickness x:Key="ButtonMargin">6</Thickness>

    <SetterBaseCollection x:Key="ButtonStyleSetters">
        <EventSetter Event="ButtonBase.Click" Handler="StyleClick" />
        <Setter Property="FrameworkElement.Height" Value="30" />
        <Setter Property="FrameworkElement.Margin" Value="6" />
    </SetterBaseCollection>

    <Style TargetType="{x:Type Button}" 
           b:Behaviours.StyleSetters="{StaticResource ButtonStyleSetters}" />
    <Style TargetType="{x:Type ToggleButton}"
           b:Behaviours.StyleSetters="{StaticResource ButtonStyleSetters}" />
    <Style TargetType="{x:Type CheckBox}">
        <EventSetter Event="Click" Handler="StyleClick" />
    </Style>
    <Style TargetType="{x:Type b:MultiCommandButton}"
           b:Behaviours.StyleSetters="{StaticResource ButtonStyleSetters}" />

    <Style TargetType="UniformGrid">
        <Setter Property="Columns" Value="2" />
    </Style>

    <CommandBindingCollection x:Key="OutputToggleReceiveAll">
        <b:OutputToggleBind />
        <b:OutputToggleEnabledBind />
    </CommandBindingCollection>

</Window.Resources>

The behaviour

public static class Behaviours
{
    #region AP CommandReceivers

    public static readonly DependencyProperty CommandReceiversProperty =
        DependencyProperty.RegisterAttached(
            "CommandReceivers", typeof(CommandBindingCollection),
            typeof(Behaviours),
            new PropertyMetadata(default(CommandBindingCollection),
                (t, a) => UpdateCollection<CommandBindingCollection, UIElement>
                    (t, a, "CommandBindings")));

    public static void SetCommandReceivers(DependencyObject element,
        CommandBindingCollection value)
    {
        element.SetValue(CommandReceiversProperty, value);
    }

    public static CommandBindingCollection GetCommandReceivers(
        DependencyObject element)
    {
        return (CommandBindingCollection) element
            .GetValue(CommandReceiversProperty);
    }

    #endregion

    #region AP StyleSetters

    public static readonly DependencyProperty StyleSettersProperty =
        DependencyProperty.RegisterAttached(
            "StyleSetters", typeof(SetterBaseCollection),
            typeof(Behaviours),
            new PropertyMetadata(default(SetterBaseCollection),
                (t, a) => UpdateCollection<SetterBaseCollection, UIElement>
                    (t, a, "Setters")));

    public static void SetStyleSetters (DependencyObject element,
        SetterBaseCollection value)
    {
        element.SetValue(StyleSettersProperty, value);
    }

    public static SetterBaseCollection GetStyleSetters (
        DependencyObject element)
    {
        return (SetterBaseCollection)element
            .GetValue(StyleSettersProperty);
    }

    #endregion

    private static void UpdateCollection<TCollection, THost> (
        DependencyObject target, DependencyPropertyChangedEventArgs args, 
        string targetCollection)
        where TCollection : IList
        where THost : class
    {
        var host = target as THost;
        if (host == null) return;

        var collection = typeof(THost).GetProperty(targetCollection)
            .GetValue(host) as IList;
        if (collection == null) return;

        if (args.OldValue != null)
        {
            foreach (var member in
                (TCollection) args.OldValue)
            {
                collection.Remove(member);
            }
        }
        if (args.NewValue != null)
        {
            foreach (var member in
                (TCollection) args.NewValue)
            {
                collection.Add(member);
            }
        }
    }
}

The question

I think I probably have to add an OnAttached handler as well but am I doing anything wrong in the xaml? It's nagging that the attached property was not found but this is commonly not a problem and I would expect it to disappear once the assembly compiles successfully.

EDIT

Based on feedback from @mm8 and this answer, I tried the following approach but, also throws.

View

<Window.Resources>

    <SetterBaseCollection x:Key="ButtonStyleSetters">
        <EventSetter Event="ButtonBase.Click" Handler="StyleClick" />
        <Setter Property="FrameworkElement.Height" Value="30" />
        <Setter Property="FrameworkElement.Margin" Value="6" />
    </SetterBaseCollection>

    <Style TargetType="{x:Type Button}" >
        <Setter Property="local:Behaviours.StyleSetters" 
                Value="{StaticResource ButtonStyleSetters}"/>
    </Style>

</Window.Resources>

In Behaviour class

public static readonly DependencyProperty StyleSettersProperty =
    DependencyProperty.RegisterAttached(
        "StyleSetters", typeof(SetterBaseCollection),
        typeof(Behaviours),
        new PropertyMetadata(default(SetterBaseCollection),
            (t, a) => UpdateCollection<SetterBaseCollection, Style>
                (((FrameworkElement)t).Style, a, "Setters")));

public static void SetStyleSetters (DependencyObject element,
    SetterBaseCollection value)
{
    element.SetValue(StyleSettersProperty, value);
}

public static SetterBaseCollection GetStyleSetters (
    DependencyObject element)
{
    return (SetterBaseCollection)element
        .GetValue(StyleSettersProperty);
}

#endregion

private static void UpdateCollection<TCollection, THost> (
    object target, DependencyPropertyChangedEventArgs args, 
    string targetCollection)
    where TCollection : class, IList
    where THost : class
{
    var host = target as THost;
    if (host == null) return;

    var collection = typeof(THost).GetProperty(targetCollection)
        .GetValue(host) as IList;
    if (collection == null) return;

    var oldValue = args.OldValue as TCollection;
    if (oldValue != null)
    {
        foreach (var member in oldValue)
        {
            collection.Remove(member);
        }
    }
    try
    {
        var newValue = args.NewValue as TCollection;
        if (newValue != null)
        {
            foreach (var member in newValue)
            {
                collection.Add(member);
            }
        }

    }
    catch (Exception e)
    {
        Debug.WriteLine("{0} in UpdateCollection<TCollection, THost>");
    }
}

The value of the StaticResource is always null.
The OnPropertyChanged callback is hit every time the property is set on a button and the button is passed as the first argument.

Community
  • 1
  • 1
Cool Blue
  • 6,438
  • 6
  • 29
  • 68

1 Answers1

0

A Style is not a DependencyObject so you won't be able to set your StyleSetters attached property on a Style.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Is there another way? I tried a different approach that avoids this problem but still not able to get it working. Do you have a view on it? – Cool Blue Jan 11 '17 at 09:07
  • I don't think so. You cannot set the Setters property of a Trigger directly to a SetterBaseCollection object which you define as a resource in XAML as the property is read-only: https://social.msdn.microsoft.com/Forums/vstudio/en-US/67f2796d-7ed2-4878-be7d-8a38c9da5dca/any-way-to-group-triggersetters-in-xaml-as-a-resource-for-referencing?forum=wpf – mm8 Jan 11 '17 at 09:55
  • It's read only but it's members are not. I should be able to add to the collection as I am in my code should I not? – Cool Blue Jan 11 '17 at 10:13
  • You can't add the setters to the Style of the Button because it is sealed. – mm8 Jan 11 '17 at 10:34
  • But the setter is only a member of the Setters Collection and it's only an attached (dependency) property, it's not attempting to set anything on the style. I don't get it... – Cool Blue Jan 11 '17 at 11:06
  • It is the Setters collection that is sealed, i.e. you cannot add anything to it. – mm8 Jan 11 '17 at 11:12
  • OK... I'm new to this but, my understanding is that sealed only affects inheritance: a sealed class cannot be a base class and a sealed override on a virtual member of a base class, converts the member to concrete from the perspective of any further derived classes. Are you saying that it also affects mutability of instance state? – Cool Blue Jan 11 '17 at 12:36
  • This is another type of sealing...the WPF runtime seals the style for performance reasons: http://streamingcon.blogspot.se/2015/07/wpf-using-object-as-value-in-style.html – mm8 Jan 11 '17 at 12:44
  • 1
    Ah, OK. Yes, I saw that in the source code: `IsSealed`. I think I've hit my WPF WTF sealing (sic). I'll stop bothering you and have a read of the blog. Cheers! – Cool Blue Jan 11 '17 at 12:47