我正在創建一個應用程序,用於在單個窗口中編輯大量產品規格。使用DataTemplate在ContentControl中指定靜態文本值
我有一堆尺寸(以英寸爲單位),我想創建一個簡單的模板,它將顯示每個維度的值作爲分數和小數值。它基本上是一個TextBlock和兩個TextBox。
但我想不出如何指定TextBlock的文本(在這種情況下,寬度)。
我想能夠在ContentControl聲明(或類似的東西)中指定它。
這裏是我的DataTemplate:
<Window.Resources>
<DataTemplate x:Key="InchesInputTemplate">
<StackPanel>
<TextBlock Text="{Binding}" /> <!-- How should I define the binding ? -->
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content, Converter=InchesToFractionConverter}" />
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
,然後我用它在ContentControl中:
<ContentControl Content="{Binding Width}"
ContentTemplate="{StaticResource InchesInputTemplate}"
LabelText="Width :" />
我的簡化產品類(它將包含更多的維度):
public class Product
{
private string _productCode;
public string ProductCode
{
get { return _productCode; }
set { _productCode = value; }
}
private float _width;
public float Width
{
get { return _width; }
set { _width = value; }
}
}
什麼是指定我的每個維度的Label的文本的最佳方式(LabelText pr在我的例子operty)?
您綁定的英寸屬性在哪裏?浮點寬度屬性與您綁定到內容的屬性不同嗎?如果你傳遞一個複雜的對象(帶有一個英寸屬性)作爲內容,你可以添加更多的屬性,並綁定到模板內。 –
@John Bowen你說得對,我在這裏犯了一個錯誤。起初我想爲我的維度製作一個複雜的對象,但我意識到這不是必需的。我糾正了綁定表達。 – igelineau
這樣做更有意義,但新的綁定是不必要的複雜。父控件的內容已經是模板中的DataContext,因此您可以使用{Binding Converter = InchesToFractionConverter} –