WPF'de özel bir denetim var. Bu ben int
türünde bir DependencyProperty
var. Özel denetimin şablonunda bir TextBlock
var, ve ben TextBlock
içinde tamsayı değerini göstermek istiyorum. Ama işe yaramayacağım.WPF: TemplateBinding ile bir TextBlock için bir tamsayı bağlama
TemplateBinding
kullanıyorum. Aynı kodu kullanır ancak DependencyProperty
türünü string
olarak değiştirirseniz, iyi çalışır. Ama uygulamamın geri kalanının çalışması için bir tamsayı olmasını gerçekten istiyorum.
Bunu nasıl yapabilirim?
Sorunu gösteren basitleştirilmiş kod yazdım. İlk özel denetim:
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;
}
Ve Bunu varsayılan şablon:
<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>
Ve kullanımı: Yanlış
<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>
yapıyorum?
Teşekkür // David
ile ilişkili bilinen tip dönüştürücüler kullanarak geleneksel Bağlama, böyle otomatik olarak yazın dönüşüm Şiraz ayrıca kendi değer dönüştürücü (IValueConverter bakın) kodu olabilir belirtebilirsiniz senin kendi türü dönüşüm davranışı. – Aardvark
Harika çalışıyor! Teşekkürler Quartermeister! :) – haagel
@Aardvark: İyi nokta. Bir TemplateBinding kullansanız bile aslında bir Dönüştürücü belirtebilirsiniz. – Quartermeister