【问题标题】:WPF: Binding an integer to a TextBlock with TemplateBindingWPF:使用 TemplateBinding 将整数绑定到 TextBlock
【发布时间】:2011-03-05 10:15:48
【问题描述】:

我在 WPF 中有一个自定义控件。在这个我有一个int 类型的DependencyProperty。在自定义控件的模板中我有一个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>

我做错了什么?

谢谢 // 大卫

【问题讨论】:

    标签: wpf xaml binding controltemplate


    【解决方案1】:

    尝试使用普通的BindingRelativeSourceTemplatedParent

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

    根据this thread,这是TemplateBinding的限制:

    TemplateBinding 是一个轻量级的 “绑定”,它不支持某些 传统装订的特点,如 使用自动类型转换 相关的已知类型转换器 与目标属性

    【讨论】:

    • 使用像这样的常规绑定,您还可以指定自己的值转换器(请参阅 IValueConverter),您可以编写自己的类型转换行为。
    • 效果很好!谢谢季总! :)
    • @Aardvark:好点。即使使用 TemplateBinding,您实际上也可以指定 Converter。
    • 认为 Silverlight 的 TemplateBinding 版本不支持 Converter 参数 - 但我猜 WPF 支持。我的错!
    • 哇,这是救生员!可悲的部分:这在 Microsoft Expression Blend 4 中没有自动正确处理
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多