Disaji
Disaji

Reputation: 99

WPF DateTimePicker or two textboxes (one for date, one for time) same database binding for show and handle date and time

I have a datetime database field. In my application I have two textbox binding to that field.

One have the string format :date ,while the other has format:time. the problem is that only when the user updates the date or the time, the other textbox (date or time) reset itself.

I also tried to work with wpf toolkit but I find it difficult to field update.

<TextBox Name="txtDate" Text="{Binding Documenti,                                    
               StringFormat=\{0:d\}}" /> 
<TextBox Name="txtTime" Text="{Binding Documenti,
               StringFormat=\{0:hh:mm\}}"/>-->

Upvotes: 0

Views: 798

Answers (1)

grek40
grek40

Reputation: 13438

You have to separate the properties in order to apply a custom logic in setter, where changed parts are merged with unchanged parts.

DataContext

public class MyViewModel : INotifyPropertyChanged
{
    private DateTime _Documenti;
    public DateTime Documenti
    {
        get { return _Documenti; }
        set
        {
            if (_Documenti != value)
            {
                _Documenti = value;
                RaisePropertyChanged("Documenti");
                RaisePropertyChanged("DatePart");
                RaisePropertyChanged("TimePart");
            }
        }
    }

    public DateTime DatePart
    {
        get { return Documenti; }
        set
        {
            Documenti = new DateTime(value.Year, value.Month, value.Day, Documenti.Hour, Documenti.Minute, Documenti.Second);
        }
    }
    public DateTime TimePart
    {
        get { return Documenti; }
        set
        {
            Documenti = new DateTime(Documenti.Year, Documenti.Month, Documenti.Day, value.Hour, value.Minute, value.Second);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void RaisePropertyChanged(string prop)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
    }
}

XAML

<TextBox Name="txtDate" Text="{Binding DatePart,                                    
       StringFormat=\{0:d\}}" />
<TextBox Name="txtTime" Text="{Binding TimePart,
       StringFormat=\{0:hh:mm\}}" />

Upvotes: 1

Related Questions