Tôi có một điều khiển tùy chỉnh trong WPF. Trong này tôi có một DependencyProperty
của loại int
. Trong mẫu cho điều khiển tùy chỉnh, tôi có một số TextBlock
, tôi và muốn hiển thị giá trị của số nguyên trong số TextBlock
. Nhưng tôi không thể làm cho nó hoạt động được.WPF: Ràng buộc một số nguyên vào một TextBlock với TemplateBinding
Tôi đang sử dụng TemplateBinding
. Nếu tôi sử dụng cùng một mã nhưng thay đổi loại của DependencyProperty
thành string
thì nó hoạt động tốt. Nhưng tôi thực sự muốn nó là một số nguyên cho phần còn lại của ứng dụng của tôi để làm việc.
Tôi làm cách nào để thực hiện việc này?
Tôi đã viết mã đơn giản hiển thị sự cố. Đầu tiên điều khiển tùy chỉnh:
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;
}
Và đây là mẫu mặc định của tôi:
<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>
Và sử dụng:
<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>
Tôi đang làm gì sai?
Cảm ơn // David
Sử dụng thường xuyên Ràng buộc như thế này bạn cũng có thể chỉ định chuyển đổi của riêng giá trị (xem IValueConverter) mà bạn có thể mã hóa của bạn hành vi chuyển đổi loại của riêng mình. – Aardvark
Hoạt động tuyệt vời! Cảm ơn bạn Quartermeister! :) – haagel
@Aardvark: Điểm tốt. Bạn thực sự có thể chỉ định một Trình chuyển đổi ngay cả khi bạn sử dụng một TemplateBinding. – Quartermeister