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

16

我在WPF中有一个自定义控件,其中包含一个类型为intDependencyProperty。在自定义控件的模板中,我有一个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;
}

这是我的默认模板:

<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>

我做错了什么?

谢谢 // David

1个回答

23

尝试使用TemplatedParent作为RelativeSource,并搭配一个常规的Binding

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

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

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


使用常规绑定,您还可以指定自己的值转换器(请参见IValueConverter),以编写自己的类型转换行为。 - Aardvark
运行得很好!谢谢Quartermeister! :) - haagel
@Aardvark:说得好。即使使用TemplateBinding,您实际上也可以指定转换器。 - Quartermeister
我认为Silverlight的TemplateBinding版本不支持Converter参数,但我猜WPF支持。我的错误! - Aardvark
哇,这真是救命稻草!不幸的是:在Microsoft Expression Blend 4中,这并没有被自动正确处理。 - user46915

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接