我有多个TextBlocks,它引用了我的应用程序中的不同元素.我的代码在页面中直接使用时工作正常.但是,我想创建一个ControlTemplate和一个ContentControl来减少代码的重复.
如何使用TemplateBinding从ContentControl传递对ElementName的引用到ControlTemplate?以下代码抛出此错误:
"无法将属性'ElementName'中的值转换为'System.String'类型的对象.'System.Windows.TemplateBindingExpression'类型的对象无法转换为'System.String'类型."
除了Tag属性之外,我还尝试了ContentStringFormat,它也没有用.
使用模板使其工作的正确方法是什么?
在此先感谢您的帮助,
---肖恩
这是代码示例:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Page.Resources>
<ControlTemplate x:Key="MyTemplate" TargetType="{x:Type ContentControl}">
<TextBlock Margin="{Binding ElementName={TemplateBinding Tag}, Path=Margin}" Text="{TemplateBinding Content}" TextAlignment="{Binding ElementName={TemplateBinding Tag}, Path=TextAlignment}" Width="{Binding ElementName={TemplateBinding Tag}, Path=Width}" />
</ControlTemplate>
</Page.Resources>
<StackPanel>
<TextBlock x:Name="AnotherElement" Margin="10" Text="Main TextBlock" TextAlignment="Center" Width="100" />
<TextBlock x:Name="AnotherElement2" Margin="20" Text="Second TextBlock" TextAlignment="Left" Width="250" />
<TextBlock Margin="{Binding ElementName=AnotherElement, Path=Margin}" Text="Here is my TextBlock!" TextAlignment="{Binding ElementName=AnotherElement, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement, Path=Width}" />
<TextBlock Margin="{Binding ElementName=AnotherElement2, Path=Margin}" Text="Here is my Second TextBlock!" TextAlignment="{Binding ElementName=AnotherElement2, …Run Code Online (Sandbox Code Playgroud)