سؤال

In my WPF application, I have a static List<Guest>. Guest has properties like Name, Lastname, Birthday, etc.

My question concerns Birthday. I would like to display Birthday, which is of type DateTime, in a TextBlock. The output format that I want is something like DD/MM/YYYY. I've thought of using a parsing approach like this:

DateTime.ParseExact(s, "yyyyMMdd").ToLocalTime()

Is there a better way to go that avoids this kind of parsing? For instance, does C# have a converter for DateTime? Note that I need to do this conversion only for output.

هل كانت مفيدة؟

المحلول

The painful way is to make it manually with formatting and parsing. The elegant way is to bind your form to an object containing your properties. When using object-data binding you can specify formats. The conversions in both ways are carried out automatically.

Besides the advantage of having an automatic conversion to and from strings, you have the advantage that you can separate the business logic from your form. You can apply any logic to a property called guest.DateOfBirth (or just DateOfBirth if the logic is inside the Guest class), for instance, instead of applying it to a construct like DateTime.Parse(textBox13.Text), which makes it a lot easier to understand and maintain the code.

See:

Data Binding for Windows Forms (on developerfusion)

Data binding concepts in .NET windows forms (on CodeProject)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top