控件模板中的模板绑定
我有以下控制模板。
我希望在控件中设置图像控件的源属性 使用模板绑定的模板。
但由于这是按钮控件的控件模板,而按钮控件不 有源属性,在这种情况下我不能使用 TemplateBinding。
<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>
由于我必须为按钮的不同实例设置不同的图像,因此我也无法对路径进行硬编码。
请让我知道如何解决这种情况。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用动态资源,例如定义模板如下:
并像这样使用它:
I'd suggest using dynamic resources, e.g. define the template as follows:
And use it like this:
TemplateBinding 是一个轻量级的“绑定”,它不支持传统 Binding 的某些功能,例如使用与目标属性关联的已知类型转换器进行自动类型转换(例如将字符串 URI 转换为 BitmapSource 实例)。
下面的代码可以正常运行:
TemplateBinding is a lightweight "binding", it doesn't support some features of traditional Binding, such as automatically type conversion using the known type converters associated with the target property (such as converting the string URI into a BitmapSource instance).
The following code can work properly:
您还没有真正说出您期望按钮的使用者如何设置源。例如,您可以使用
Button.Tag
属性,然后绑定到模板中的该属性。或者您可以定义自己的控件:然后是模板:
You haven't really said how you expect consumers of your button to set the source. You could use the
Button.Tag
property, for example, and then bind to that in your template. Or you could define your own control:And then the template:
我不确定我是否很好地理解你的问题,但你为什么不使用 ContentPresenter 呢?它允许在更高级别移动图像的代码。
I'm not sure that I understood your problem very well but why don't you use ContentPresenter? It allows to move the code for your Image at the higher level.