开发者

How to get image source in Control Template

I've added one button like this:

<Button x:Name="myButton" 
            Style="{StaticResource myButtonStyle}" 
            Height="36" 
            VerticalAlignment="Top"
            Click="myButton_Click">

        <Grid>
            <Image Height="*" Width="31" Source="{Binding Path=Image}" />
            <TextBlock Text="{Binding Path=DisplayName}" HorizontalAlignment="Center" />
        </Grid>
</Button>

Where 'Image' is the source of the required image in string. And the style is as follows:

<Style x:Key="myButtonStyle"
     TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">

                        <Border x:Name="myButtonRootBorder">

                                <StackPanel Orientation="Horizontal">
                                    <Image Source="{??}" Width="{??}" Height="{??}" />
                                    <!--ContentPresenter-->
                                    <ContentPresenter Grid.Column="1"
                                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                                    开发者_运维技巧VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                                    Content="{TemplateBinding Content}" />
                                </StackPanel
                        </Border>
                    </Grid>
                </ControlTemplate> 
            </Setter.Value>
        </Setter>
    </Style>

Now how to set the height, width and source of the image in the control template.

Please help. Thanks in advance.


For width and height you can use {TemplateBinding Width} and {TemplateBinding Height}. If you want the image to be customizable you should inherit the button class and add an imagesource property:

public class ImageButton : Button {
        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ImageSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null));
}

Then you can use {TemplateBinding ImageSource} for the image.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜