Search code examples
c#wpfxamlenumsattached-properties

Bind enum value to attached property in XAML


I have the following class which has an enum and an attached property.

namespace U.Helpers
{
    public enum SearchDirection
    {
        Forward,
        Backward
    }
    public class TargetedTriggerActionFindNextButton : TargetedTriggerAction<DataGrid>
    {
        protected override void Invoke(object parameter)
        {
            if (SearchDirectionControl == SearchDirection.Forward)
                //Do something
            else
                //Do something else
            }

        public static readonly DependencyProperty SearchDirectionControlProperty =
            DependencyProperty.Register("SearchDirectionControl", typeof(object), typeof(TargetedTriggerActionFindNextButton), new PropertyMetadata(SearchDirection.Forward));

        public SearchDirection SearchDirectionControl
        {
            get { return (SearchDirection)GetValue(SearchDirectionControlProperty); }
            set { SetValue(SearchDirectionControlProperty, value); }
        }
    }
}

Here is my XAML so far:

<UserControl x:Class="UM.LaunchPad"
             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"
             xmlns:helpers="clr-namespace:UM.Helpers">

    <Grid Name="gridUsers" Background="Transparent">
        <Button Name="SearchNextButton" Content="Next" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <helpers:TargetedTriggerActionFindNextButton TargetObject="{Binding ElementName=GenericDataGrid}" 
                             SearchDirectionControl="{Binding helpers:SearchDirection.Forward}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
    </Grid>
</UserControl>

I am wondering how to add an enum value to my attached property on the XAML side. See the button's SearchDirectionControl.


Solution

  • Do not use a binding when you want to refer to a specific Enum value, but use the x:Static Markup Extension instead:

    <helpers:TargetedTriggerActionFindNextButton
        TargetObject="{Binding ElementName=GenericDataGrid}" 
        SearchDirectionControl="{x:Static helpers:SearchDirection.Forward}"
    />
    


    Quoting the MSDN documentation of x:Static:

    References any static by-value code entity that is defined in a Common Language Specification (CLS)–compliant way.
    [...]
    The code entity that is referenced must be one of the following:

    A constant
    A static property
    A field   [sic; it should be a "static field", obviously]
    An enumeration value