我有多個TextBlocks在我的應用程序中引用不同的元素。我的代碼直接在頁面中使用時工作正常。不過,我想創建一個ControlTemplate和一個ContentControl來減少代碼的重複。如何使用ControlTemplate中的ElementName綁定?
如何將使用TemplateBinding的ContentControl的引用傳遞到ControlTemplate中?以下代碼將引發此錯誤:
"Cannot convert the value in attribute 'ElementName' to object of type 'System.String'. Object of type 'System.Windows.TemplateBindingExpression' cannot be converted to type '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, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement2, Path=Width}" />
<ContentControl Content="Hello!" Tag="AnotherElement" Template="{StaticResource MyTemplate}" />
<ContentControl Content="Hello Again!" Tag="AnotherElement2" Template="{StaticResource MyTemplate}" />
</StackPanel>
</Page>
爲什麼不創建樣式並將其應用於所有需要該樣式的控件?爲什麼要在一個控件上定義一些屬性,然後將其他控件綁定到它?這聽起來很奇怪。 – 2013-03-07 23:25:13
@Brent將信息存儲在Tag屬性中,曾經是MS Access表單開發的技術。將一些硬編碼值傳遞給綁定到您控件上的某個屬性/處理函數的VBA函數是一種便宜而又糟糕的方式。我們不需要WPF,因爲我們有更多的工具可供我們使用=) – failedprogramming 2013-03-08 08:17:48
@BrentStewart該實現的最終結果是使用MVVM,Bindings,DataTemplates等在列中顯示信息。我特意縮小了我的示例在這個網站上詢問。我選擇不使用Grid,而是使用WrapPanel,因爲我覺得使用它更簡單,更清潔。我將一個TextBlock的幾個屬性綁定到另一個是因爲我希望我的列值複製我爲其特定標題(邊距,寬度,對齊方式等)設置的屬性。你將如何實現這個使用樣式時,每個文本塊它會引用一個不同的元素名稱? – 2013-03-08 16:18:01