I'm trying to bind an integer to a ControlTemplate but shows nothing to me.
here is my TextBlock
which is a part of my ControlTemplate
:
<TextBlock FontSize="14"
Foreground="#000"
Text="{TemplateBinding Number}"/>
here is my dependency property which is a part of my CustomControl:
public static readonly DependencyProperty NumberProperty = DependencyProperty.Register(nameof(Number), typeof(int), typeof(MyCustomControl), new PropertyMetadata(0));
public int Number
{
get => (int)GetValue(NumberProperty);
set => SetValue(NumberProperty, value);
}
I have tried this also, but it doesn't works too:
<TextBlock FontSize="14"
Foreground="#000"
Text="{Binding Number, RelativeSource={RelativeSource TemplatedParent}, TargetNullValue=''}"/>
if I change it to string
it works 😢
You have to use a converter which will convert int to string value. Here's the example of such converter.
public sealed class IntToStringConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object parameter, string language)
{
return ((int)value!).ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Instead of the TemplatedBinding
in the control template you should use such statement.
<TextBlock FontSize="14" Foreground="#000"
Text="{Binding Number, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource IntToStringConverter}}" />
One more thing. You have to define the converter somewhere in your xaml to be able to use it as a StaticResource
.
<c:IntToStringConverter x:Key="IntToStringConverter" />
Update
Converter is not needed to show integer value as text.
//Working
Text="{Binding Number, RelativeSource={RelativeSource Mode=TemplatedParent}}"
//Not working
Text="{TemplateBinding Number}"