WPF:使用TemplateBinding將整數繫結到TextBlock
我在WPF中有一個自定義控制元件.在這裡我有一個型別為int的DependencyProperty.在自定義控制元件的模板中,我有一個TextBlock,我想在TextBlock中顯示整數的值.但我不能讓它上班.
我正在使用TemplateBinding.如果我使用相同的程式碼,但將DependencyProperty的型別更改為字串,那麼它可以正常工作.但我真的希望它是一個整數,我的應用程式的其餘部分工作.
我該怎麼做?
我已經編寫了簡化的程式碼來顯示問題.首先定製控制元件:
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>
我究竟做錯了什麼?
謝謝//大衛
<TextBlock Text="{Binding MyInteger, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Center" />
根據ofollow,noindex" target="_blank">this thread ,這是TemplateBinding的一個限制:
TemplateBinding is a lightweight“binding”, it doesn’t support somefeatures of traditional Binding, suchas automatically type conversion usingthe known type converters associatedwith the target property
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/3069753/wpf-binding-an-integer-to-a-textblock-with-templatebinding