Binding.Format Evento
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Ocorre quando a propriedade de um controlo está vinculada a um valor de dados.
public:
event System::Windows::Forms::ConvertEventHandler ^ Format;
public event System.Windows.Forms.ConvertEventHandler Format;
member this.Format : System.Windows.Forms.ConvertEventHandler
Public Custom Event Format As ConvertEventHandler
Tipo de Evento
Exemplos
O exemplo de código seguinte cria um Binding, adiciona um ConvertEventHandler delegado tanto aos Parse eventos e Format como ao BindingBindingsCollection de um TextBox controlo através da DataBindings propriedade. O DecimalToCurrencyString delegado do evento, adicionado ao Format evento, formata o valor limitado (um Decimal tipo) como moeda usando o ToString método. O CurrencyStringToDecimal delegado do evento, adicionado ao Parse evento, converte o valor apresentado pelo controlo de volta para o Decimal tipo.
Este exemplo assume a presença de um DataSet nome ds.
private:
void DecimalToCurrencyString( Object^ /*sender*/, ConvertEventArgs^ cevent )
{
// The method converts only to string type. Test this using the DesiredType.
if ( cevent->DesiredType != String::typeid )
{
return;
}
// Use the ToString method to format the value as currency ("c").
cevent->Value = ( (Decimal)(cevent->Value) ).ToString( "c" );
}
void CurrencyStringToDecimal( Object^ /*sender*/, ConvertEventArgs^ cevent )
{
// The method converts back to decimal type only.
if ( cevent->DesiredType != Decimal::typeid )
{
return;
}
// Converts the string back to decimal using the static Parse method.
cevent->Value = Decimal::Parse( cevent->Value->ToString(),
NumberStyles::Currency, nullptr );
}
void BindControl()
{
// Creates the binding first. The OrderAmount is a Decimal type.
Binding^ b = gcnew Binding(
"Text",ds,"customers.custToOrders.OrderAmount" );
// Add the delegates to the event.
b->Format += gcnew ConvertEventHandler( this, &Form1::DecimalToCurrencyString );
b->Parse += gcnew ConvertEventHandler( this, &Form1::CurrencyStringToDecimal );
text1->DataBindings->Add( b );
}
private void DecimalToCurrencyString(object sender, ConvertEventArgs cevent)
{
// The method converts only to string type. Test this using the DesiredType.
if(cevent.DesiredType != typeof(string)) return;
// Use the ToString method to format the value as currency ("c").
cevent.Value = ((decimal) cevent.Value).ToString("c");
}
private void CurrencyStringToDecimal(object sender, ConvertEventArgs cevent)
{
// The method converts back to decimal type only.
if(cevent.DesiredType != typeof(decimal)) return;
// Converts the string back to decimal using the static Parse method.
cevent.Value = Decimal.Parse(cevent.Value.ToString(),
NumberStyles.Currency, null);
}
private void BindControl()
{
// Creates the binding first. The OrderAmount is a Decimal type.
Binding b = new Binding
("Text", ds, "customers.custToOrders.OrderAmount");
// Add the delegates to the event.
b.Format += new ConvertEventHandler(DecimalToCurrencyString);
b.Parse += new ConvertEventHandler(CurrencyStringToDecimal);
text1.DataBindings.Add(b);
}
Private Sub DecimalToCurrencyString(sender As Object, cevent As _
ConvertEventArgs)
' The method converts only to string type. Test this using the DesiredType.
If cevent.DesiredType IsNot GetType(String) Then
Exit Sub
End If
' Use the ToString method to format the value as currency ("c").
cevent.Value = CType(cevent.Value, Decimal).ToString("c")
End Sub
Private Sub CurrencyStringToDecimal(sender As Object, cevent As _
ConvertEventArgs)
' The method converts back to decimal type only.
If cevent.DesiredType IsNot GetType(Decimal) Then
Exit Sub
End If
' Converts the string back to decimal using the static ToDecimal method.
cevent.Value = Decimal.Parse(cevent.Value.ToString, _
NumberStyles.Currency, nothing)
End Sub
Private Sub BindControl
' Creates the binding first. The OrderAmount is a Decimal type.
Dim b As Binding = New Binding _
("Text", ds, "customers.custToOrders.OrderAmount")
' Add the delegates to the event
AddHandler b.Format, AddressOf DecimalToCurrencyString
AddHandler b.Parse, AddressOf CurrencyStringToDecimal
text1.DataBindings.Add(b)
End Sub
Observações
O Format evento é ativado quando os dados são enviados da fonte de dados para o controlo. Pode gerir o Format evento para converter dados não formatados da fonte de dados em dados formatados para exibição. Quando os dados são retirados do controlo para a fonte de dados, o Parse evento é levantado para desformatar o valor apresentado, e depois ocorre o Format evento para reformatar os dados para visualização. Isto garante que o controlo limitado exibe dados corretamente formatados, independentemente de o utilizador inserir dados formatados ou não no controlo.
Os Format eventos e Parse permitem criar formatos personalizados para mostrar dados. Por exemplo, se os dados numa tabela forem do tipo Decimal, pode mostrar os dados no formato de moeda local definindo a Value propriedade de o ConvertEventArgs valor formatado no Format evento. Deve, consequentemente, desformatar o valor apresentado no Parse evento.
O Format evento ocorre sempre que o Current valor dos BindingManagerBase objetos muda, o que inclui:
Na primeira vez, a propriedade é encadernada.
Sempre que as Position mudanças acontecem.
Sempre que a lista ligada a dados é ordenada ou filtrada, o que acontece quando um DataView fornece a lista.
O Format evento também ocorre após o Parse evento. Por exemplo, quando um controlo perde o foco, o seu conteúdo é analisado. Imediatamente a seguir, à medida que novos dados são inseridos no controlo, ocorre o Format evento que permite formatar o novo conteúdo.
Para obter mais informações sobre como manipular eventos, consulte Manipulando e gerando eventos.