我在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>
我做错了什么?
谢谢 // David