0
votes

I know that Silverlight 5 introduces the data binding in styles. I want to bind the source of image which is present in content template in the style of a button. I am using the below code where I am trying to set the image source property in style.

// Style

<UserControl x:Class="MGPIControls_Simple.ButtonControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
    Height="40" Width="40"
    mc:Ignorable="d" x:Name="ButtonControlSample">

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.Resources>

        <Style x:Key="ImageButtonStyle" TargetType="Button">
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>

                        <!-- binding in style -->
                        <Image Source="{Binding ImageSource}"
                               VerticalAlignment="Stretch"
                               HorizontalAlignment="Stretch"
                               Stretch="Fill"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>

        </Style>
    </Grid.Resources>
    <Button x:Name="ButtonBase" Style="{StaticResource ImageButtonStyle}"
            HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>

Where ImageSource is the dependency property I have created. If I dont bind the image source property and keep it static to some image url the things are working fine but binding is not working. Please let me know where I am wrong in above approach.

2
Where is this property ImageSource defined? Is it present in the DataContext? - Martin

2 Answers

0
votes

You have to use binding like

<TextBlock Text="{Binding Path=DataContext.BusyText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
0
votes

Well, how to put this... what you try to do is not the new Silverlight 5 feature Binding in Styles. This kind of binding is always possible, even with older Silverlight versions. You have a DataTemplate and that means any binding you declare is evaluated when actual UI elements are instantiated from the template. And your binding Source="{Binding ImageSource}" is evaluated against your Button's DataContext. If there is no public property ImageSource then your Button won't show any image.