Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a DependencyProperty to a Button?

I'm basically just trying to add a couple properties to a button to store some extra information to be used later. My choice to do this instead of creating a UserControl based on a Button was solely because it seemed like less code.

I've followed the examples I've seen on Microsoft's site and I'm getting the error "A 'Binding' cannot be set on the 'SetSortIndicatorVisibility' property of type 'Button'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject." It doesn't make sense because a Button is a DependencyObject and I'm adding a DependencyProperty. I initially started with an AttachedProperty but I've since fixed that. I've even taken all my code that relates to this and put it in a test project and I'm still getting this error. All of this test code is below:

DependencyProperty Definition:

public static readonly DependencyProperty SortIndicatorVisibilityProperty = DependencyProperty.Register( "SortIndicatorVisibility", typeof( Visibility ), typeof( Button ), new FrameworkPropertyMetadata( Visibility.Visible, FrameworkPropertyMetadataOptions.AffectsRender ) );

    public static void SetSortIndicatorVisibility( Button button, Visibility value )
    {
        button.SetValue( SortIndicatorVisibilityProperty, value );
    }
    public static Visibility GetSortIndicatorVisibility( Button button )
    {
        return ( Visibility ) button.GetValue( SortIndicatorVisibilityProperty );
    }

Window XAML containing the button with the new property and the binding:

<Window x:Class="Testing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ext="clr-namespace:Testing"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="Test"
            Command="{Binding TestCommand}"
            ext:Class1.SortIndicatorVisibility="{Binding SortIndicatorVisibilitySiteName}" />
</Grid>

Lastly, the property the DependencyProperty is bound to:

public Visibility SortIndicatorVisibilitySiteName
    {
        get
        {
            return Visibility.Visible;
        }
    }
like image 780
Ben Avatar asked Jan 15 '11 20:01

Ben


1 Answers

You can't add a "normal" dependency property to an arbitrary class, it has to be an attached property. Also, the owner type shouldn't be Button, it should be the class that declares the property

like image 120
Thomas Levesque Avatar answered Oct 03 '22 02:10

Thomas Levesque