当我在按钮模板上工作时,我刚刚遇到绑定StringFormat问题。这里是。绑定StringFormat的自定义按钮模板问题
- 我设置了一个具有给定工具提示的按钮作为字符串。我喜欢用它来指定绑定中的图像名称。然后我将它应用到名为ImageButton的按钮样式。
<Button ToolTip="Minimize" Height="34" Style="{StaticResource ImageButton}" Margin="220,36,125,371" />;
- 这是风格的代码。我喜欢使用绑定中的图像名称,并提供完整的图像路径。它应该是这样工作的,<Image x:Name="ButtonImage" Source="Images/Minimize-Normal.png" />
。是的,我确实有这样一个图像,如果我只是把xml代码没有绑定的话,它就很好用。
<Image x:Name="ButtonImage" Source="{Binding ToolTip, RelativeSource={RelativeSource TemplatedParent}, StringFormat={}Images/{0}-Normal.png}" />
但绑定没有按预期工作。图像无法正确显示。如果我把图像全名放在工具提示中,那么它的工作是正确的。它看起来像StringFormat已被忽略。
任何帮助将不胜感激。提前致谢。
感谢dbaseman的回应。我知道我可以通过使用Converter来实现它。但正如我认为StringFormat更容易应用,这就是为什么我尝试了这一点。
我还在这里找到了答案,它说 - StringFormat用于绑定到字符串属性,而控件中的Text属性是类型对象,因此StringFormat被忽略。
它应该是设计。下面的代码工作。因为Text属性是字符串类型。
<TextBlock Text="{Binding ToolTip, RelativeSource={RelativeSource Self}, StringFormat={}Images/{0}-Normal.png}" ToolTip="Minimize" />