2010-06-18 70 views
15

我在WPF中有一個自定義控件。在這我有一個DependencyPropertyint類型。在自定義控件的模板中,我有一個TextBlock,我希望在TextBlock中顯示整數的值。但我無法讓它工作。我正在使用TemplateBinding。如果我使用相同的代碼,但將DependencyProperty的類型更改爲string它可以正常工作。但我真的希望它成爲我的應用程序的其餘工作的整數。WPF:使用TemplateBinding將整數綁定到TextBlock

我該怎麼做?

我寫了簡化的代碼來顯示問題。首先自定義控件:

public class MyCustomControl : Control 
{ 
    static MyCustomControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); 

     MyIntegerProperty = DependencyProperty.Register("MyInteger", typeof(int), typeof(MyCustomControl), new FrameworkPropertyMetadata(0)); 
    } 


    public int MyInteger 
    { 
     get 
     { 
      return (int)GetValue(MyCustomControl.MyIntegerProperty); 
     } 
     set 
     { 
      SetValue(MyCustomControl.MyIntegerProperty, value); 
     } 
    } 
    public static readonly DependencyProperty MyIntegerProperty; 
} 

這是我的默認模板:

<Style TargetType="{x:Type local:MyCustomControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:MyCustomControl}"> 
       <Border BorderThickness="1" CornerRadius="4" BorderBrush="Black" Background="Azure"> 
        <StackPanel Orientation="Vertical"> 
         <TextBlock Text="{TemplateBinding MyInteger}" HorizontalAlignment="Center" /> 
        </StackPanel> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

與用法:

<Window x:Class="CustomControlBinding.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:CustomControlBinding" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <local:MyCustomControl Width="100" Height="100" MyInteger="456" /> 
</Grid> 

我在做什麼錯?

感謝//大衛

回答

17

嘗試使用普通BindingTemplatedParentRelativeSource

<TextBlock Text="{Binding MyInteger, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Center" /> 

根據this thread,這是TemplateBinding限制:

TemplateBinding是輕量級 「綁定」,它不支持一些 fea使用 與目標屬性

+0

相關 已知的類型轉換器使用普通約束力喜歡這種傳統的綁定,例如 的自動類型轉換的功能,你也可以指定自己的值轉換器(見的IValueConverter),你可以把你自己的類型轉換行爲。 – Aardvark 2010-06-18 13:11:45

+0

很棒!謝謝Quartermeister! :) – haagel 2010-06-18 13:20:22

+0

@Aardvark:好點。即使您使用TemplateBinding,實際上也可以指定一個Converter。 – Quartermeister 2010-06-18 13:22:23