I have this XAML:
<Label Text="{Binding val1, StringFormat={StaticResource CommaInteger}}"/>
<Label Text="{Binding val2, StringFormat={StaticResource CommaInteger}}"/>
I want to simplify it to:
<local:commaIntLbl Text="{Binding val1}"/>
<local:commaIntLbl Text="{Binding val2}"/>
How should I code my commaIntLbl class to achieve this?
public class commaIntLbl : Label
{
public commaIntLbl() : base()
{
SetDynamicResource(StyleProperty, "IntegerLabel");
// How to refer its Text's string-format to the StaticResource CommaInteger?
}
}
You could set the string format in val1 property like below and then do the binding.
public string _val1;
public string val1
{
get
{
return string.Format("Hello, {0}", _val1);
}
set
{
_val1 = value;
}
}
Update:
Xaml:
<local:CommaIntLbl TextVal="{Binding val1}" />
Custom Control:
public class CommaIntLbl : Label
{
public CommaIntLbl() : base()
{ }
private string _text;
public string TextVal
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged();
}
}
public static readonly BindableProperty TextValProperty = BindableProperty.Create(
nameof(TextVal),
typeof(string),
typeof(CommaIntLbl),
string.Empty,
propertyChanged: (bindable, oldValue, newValue) =>
{
var control = bindable as CommaIntLbl;
control.Text = String.Format("Hello, {0}", newValue);
});
}
Code behind:
public string _val1;
public string val1 { get; set; }
public Page19()
{
InitializeComponent();
val1 = "1234";
this.BindingContext = this;
}