Home > Enterprise >  DataGrid DatePickertemplate WPF
DataGrid DatePickertemplate WPF

Time:09-28

I have a WPF application and a problem with a DatePicker in a DataTemplate from a datagrid.

I assoume, that the binding has the wrong Path (WTimeClockOverviewVM instead of ClassTimeTrackingTimeStamp).

However, when I try to bind the propertie, the datepicker control is empty.

The first binding (id) works successfully.

Does someone have any idea?

XAML:

<DataGrid Grid.Column="0"
    Grid.Row="1"
    x:Name="DgStempelungen"
    Margin="0 10 10 0"
    AutoGenerateColumns="False"
    CanUserAddRows="True"
    SelectedItem="{Binding SelectedValue}"
    ItemsSource="{Binding TimeDetailList}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding  Id}"/>
        <DataGridTemplateColumn Header="KOMMEN DATUM">
              <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DatePicker Text="{Binding ComeBooking}"/>
                    </DataTemplate>
               </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

VIEW MODEL

[CanBeNull] 
private ObservableCollection<ClassTimeTrackingTimeStamp> _timeDetailList;

[CanBeNull]
public ObservableCollection<ClassTimeTrackingTimeStamp> TimeDetailList
{
    get { return _timeDetailList; }
    set
    {
        _timeDetailList = value;
        OnPropertyChanged();
    }
}

MODEL

public class ClassTimeTrackingTimeStamp
{
    public DateTime ComeBooking { get; set; }
    public DateTime GoBooking { get; set; }
    public int Id { get; set; }

    public string Info { get; set; }
}

CodePudding user response:

Bind ComeBooking to SelectedDate property like this

<DatePicker SelectedDate="{Binding ComeBooking}"/>

To support changing DatePicker's SelectedDate from source, you ought to implement INotifyPropertyChanged

public class ClassTimeTrackingTimeStamp : INotifyPropertyChanged
{
    private DateTime _comeBooking;
    public DateTime ComeBooking
    {
        get => _comeBooking;
        set
        {
            _comeBooking = value;
            OnPropertyChanged();
        }
    }
    
    private DateTime _goBooking;
    public DateTime GoBooking
    {
        get => _goBooking;
        set
        {
            _goBooking = value;
            OnPropertyChanged();
        }
    }
    
    public int Id { get; set; }

    public string Info { get; set; }
    
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  • Related