2010-06-18 71 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