Search code examples
c#wpfbindingdatagridcell

Change the value in a cell in a datagrid (binding)


this is my issue.

When I select a single row and I click on the button, the cell must change value, but it doesn't change anything

enter image description here

This is XAML code.

        <DataGrid 

        ItemsSource="{Binding Dati_Viaggio, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
        SelectedItem="{Binding SelectDati_Viaggio, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

        AutoGenerateColumns="False" HorizontalAlignment="Left" Height="119" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">

        <DataGrid.Columns>
            <DataGridTextColumn x:Name="NumOrd" Binding="{Binding Path=NumOrd, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  Header="NumOrd" Width="150" />
        </DataGrid.Columns>

    </DataGrid>

and this is c# code

Public ObservableCollection<Model_Ricerca_Dati_Viaggio> Dati_Viaggio 
{ get; set; }
private Model_Ricerca_Dati_Viaggio _SelectDati_Viaggio;
public Model_Ricerca_Dati_Viaggio SelectDati_Viaggio {
get { return _SelectDati_Viaggio; }
set {
    _SelectDati_Viaggio = value;
    OnPropertyChanged("SelectDati_Viaggio");}}

private string _NumOrd { get; set; }
public string NumOrd {
get { return _NumOrd; }
set {
    _NumOrd = value;
    OnPropertyChanged("NumOrd");}}

Private void Cmd_TrovaExe()
{
SelectDati_Viaggio.NumOrd = Now.@string;

OnPropertyChanged("NumOrd");
OnPropertyChanged("Dati_Viaggio");
OnPropertyChanged("SelectDati_Viaggio");
}

Why the cell doesn't refres after SelectDati_Viaggio.NumOrd = Now.@string; ?


Solution

  • Your class Model_Ricerca_Dati_Viaggio must as well implements the INotifyChangedinterface in order to the changed to be exposed to the UI :

      public class Model_Ricerca_Dati_Viaggio:INotifyPropertyChanged
    {
        private string _numOrd ;
        public string NumOrd  
        {
            get
            {
                return _numOrd;
            }
    
            set
            {
                if (_numOrd == value)
                {
                    return;
                }
    
                _numOrd = value;
                OnPropertyChanged("NumOrd");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }