views:

282

answers:

2

I'm creating an attached behavior in order to set a regular property of a class:

public class LookupHelper
{
    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached("ItemsSource", typeof(object), typeof(LookupHelper), new UIPropertyMetadata(null, OnItemsSourceChanged));

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as MyControl;
        if(control == null)
                return;

        control.ItemsSource = (IEnumerable)e.NewValue;
    }

    public static object GetItemsSource(GridColumn column)
    {
        return column.GetValue(ItemsSourceProperty);
    }

    public static void SetItemsSource(GridColumn column, object value)
    {
        column.SetValue(ItemsSourceProperty, value);
    }
}   

Here, ItemsSource property on MyControl is a regular property, so I can not bind it in Xaml, hence this attached behavior.

Now, when I use this attached property using string or objects it works and breakpoint I set is hit, but when I set it with Binding markup, it never runs. Why isn't this working?

<MyControl ctrl:LookupHelper.ItemsSource="DataSource"/>; //It works
<MyControl ctrl:LookupHelper.ItemsSource="{Binding Path=MyDataSource}"/>; //Does not work

What I need to do is to set the ItemsSource property to the value specified by the Binding.

A: 

Can you please post the markup you are using? Also, If the actual property exists on an object and makes sense there then I think you should be using a regular dependency property on that object instead of an attached property on a helper class.

Edit From MSDN: The signature for the GetPropertyName accessor must be:

public static object GetPropertyName(object target)

and the signature for the SetPropertyName accessor must be:

public static void SetPropertyName(object target, object value)

In your case, is GridColumn the correct target type?

Leigh Shayler
A: 

In your Get and Set methods, you're defining the receiving object as GridColumn where it should be DependencyObject.

You might also want to change the type of your DP from object to IEnumerable since your casting to that in your change handler.

John Bowen