How to use Attached property within a style? How to use Attached property within a style? wpf wpf

How to use Attached property within a style?


Here is how you can set your attached property in a style

<Style x:Key="ToolBarButtonStyle" TargetType="Button">    <Setter Property="PrismExt:ImgSourceAttachable.ImgSource"            Value="./Images/New.png"/>    <!--...--></Style>

When binding to attached properties then the Path should be within parentheses so try to use RelativeSource Binding with TemplatedParent instead

<Setter Property="Template">    <Setter.Value>        <ControlTemplate TargetType="Button">            <Image x:Name="toolbarImage"                    Source="{Binding RelativeSource={RelativeSource TemplatedParent},                                    Path=(PrismExt:ImgSourceAttachable.ImgSource)}"                    Width="48"                    Height="48">            </Image>        </ControlTemplate>    </Setter.Value></Setter>

Edit: The above code works in WPF, in Silverlight the Image shows in runtime but it fails in the designer with an exception. You can use the following code in the PropertyChangedCallback to get the Image as a workaround

private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e){    Button button = d as Button;    Image image = GetVisualChild<Image>(button);    if (image == null)    {        RoutedEventHandler loadedEventHandler = null;        loadedEventHandler = (object sender, RoutedEventArgs ea) =>        {            button.Loaded -= loadedEventHandler;            button.ApplyTemplate();            image = GetVisualChild<Image>(button);            // Here you can use the image        };        button.Loaded += loadedEventHandler;    }    else    {        // Here you can use the image    }}private static T GetVisualChild<T>(DependencyObject parent) where T : DependencyObject{    T child = default(T);    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);    for (int i = 0; i < numVisuals; i++)    {        DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);        child = v as T;        if (child == null)        {            child = GetVisualChild<T>(v);        }        if (child != null)        {            break;        }    }    return child;}