【发布时间】: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