控件模板中的模板绑定 [英] Template Binding in Control template
问题描述
我希望使用模板绑定在控件
模板中设置图像控件的源属性。
但是,由于这是按钮控件的控件模板,按钮控件没有
具有source属性,所以在这种情况下我不能使用TemplateBinding。
< ControlTemplate x:Key =BtnTemplateTargetType =Button>
< Border CornerRadius =5Margin =15Cursor =Hand>
< StackPanel>
< Image Name =ImgStyle ={StaticResource ImageStyle}Source =temp.jpgHeight =100Width =100Margin =5>< / Image>
< Label Content ={TemplateBinding Content}Background =TransparentMargin =2>< / Label>
< / StackPanel>
< / Border>
< / ControlTemplate>
由于我必须为不同的按钮实例设置不同的图像,所以我无法将路径硬编码好。
请让我知道如何解决这种情况。
我建议使用动态资源,例如定义模板如下:
< ControlTemplate x:Key =buttonTemplateTargetType =Button>
< Border CornerRadius =5Margin =15Cursor =Hand>
< StackPanel Orientation =HorizontalBackground =Yellow>
< Image Source ={DynamicResource ResourceKey = Img}Height =100Width =100Margin =5>< / Image>
< Label Content ={TemplateBinding Content}Background =TransparentMargin =2>< / Label>
< / StackPanel>
< / Border>
< / ControlTemplate>
使用如下:
< Button Content =ButtonTemplate ={StaticResource ResourceKey = buttonTemplate}>
< Button.Resources>
< ImageSource x:Key =Img> SomeUri.png /< / ImageSource>
< /Button.Resources>
< / Button>
I have the following control template.
I wish to set the source property for the image control in the control template using Template Binding.
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>
And use it like this:
<Button Content="Button" Template="{StaticResource ResourceKey=buttonTemplate}">
<Button.Resources>
<ImageSource x:Key="Img">SomeUri.png/</ImageSource>
</Button.Resources>
</Button>
这篇关于控件模板中的模板绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!