WPF:使用TemplateBinding将整数绑定到TextBlock

haa*_*gel 15 wpf xaml binding controltemplate

我在WPF中有一个自定义控件.在这我有一个DependencyProperty类型int.在自定义控件的模板中我有一个TextBlock,我想在中显示整数的值TextBlock.但我无法让它发挥作用.

我正在使用TemplateBinding.如果我使用相同的代码,但是改变的类型DependencyProperty,以string正常工作.但我真的希望它是我的应用程序其余部分工作的整数.

我怎样才能做到这一点?

我编写了简化的代码来显示问题.首先是自定义控件:

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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的默认模板:

<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>
Run Code Online (Sandbox Code Playgroud)

用法:

<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>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

谢谢//大卫

Qua*_*ter 18

尝试使用常规BindingRelativeSourceTemplatedParent:

<TextBlock Text="{Binding MyInteger, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Center" />
Run Code Online (Sandbox Code Playgroud)

根据这个帖子,这是一个限制TemplateBinding:

TemplateBinding是一个轻量级的"绑定",它不支持传统绑定的某些功能,例如使用与目标属性关联的已知类型转换器自动进行类型转换