控制模板中的模板绑定 [英] Template Binding in Control template

查看:32
本文介绍了控制模板中的模板绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制模板.

我想在控件中设置图片控件的source属性使用模板绑定的模板.

I wish to set the source property for the image control in the control template using Template Binding.

但是由于这是一个按钮控件的控件模板,按钮控件没有有源属性,在这种情况下我不能使用 TemplateBinding.

But since this is a control template for button control and the button control doesn't have source property, i can't use TemplateBinding in this case.

<ControlTemplate x:Key="BtnTemplate" TargetType="Button">
        <Border CornerRadius="5"  Margin="15" Cursor="Hand">
            <StackPanel>
                <Image Name="Img" Style="{StaticResource ImageStyle}" Source="temp.jpg" Height="100" Width="100" Margin="5"></Image>
                <Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>
            </StackPanel>
        </Border>
    </ControlTemplate>

由于我必须为按钮的不同实例设置不同的图像,因此我也无法对路径进行硬编码.

Since i have to set different images for different instances of button, i can't hardcode the path as well.

请告诉我如何处理这种情况.

Please let me know how to tackle this situation.

推荐答案

我建议使用动态资源,例如定义模板如下:

I'd suggest using dynamic resources, e.g. define the template as follows:

<ControlTemplate x:Key="buttonTemplate" TargetType="Button">
    <Border CornerRadius="5"  Margin="15" Cursor="Hand">
        <StackPanel Orientation="Horizontal" Background="Yellow">
            <Image Source="{DynamicResource ResourceKey=Img}" Height="100" Width="100" Margin="5"></Image>
            <Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>
        </StackPanel>
    </Border>
</ControlTemplate>

并像这样使用它:

<Button Content="Button" Template="{StaticResource ResourceKey=buttonTemplate}">
    <Button.Resources>
        <ImageSource x:Key="Img">SomeUri.png/</ImageSource>
    </Button.Resources>
</Button>

这篇关于控制模板中的模板绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆