WPF DataGrid Graphs: How to Manage a Value Event

In my WPF C # project, I have a Datagrid as follows:

<DataGrid x:Name="FixedPositionDataGrid" HorizontalAlignment="Left" Margin="33,229,0,0" VerticalAlignment="Top" Width="172" Height="128" AutoGenerateColumns="False" FontSize="10" CanUserAddRows="False"> <DataGrid.Columns> <DataGridTextColumn Header="indice" Binding="{Binding index}" IsReadOnly="True"/> <DataGridTextColumn Header="%" Binding="{Binding percentage}" /> <DataGridComboBoxColumn x:Name="DataGridComboBoxColumnAlignment" Header="Allineamento barre" SelectedValueBinding="{Binding alignment}"/> </DataGrid.Columns> </DataGrid> 

I need to have an event that controls the change in value in the second and third columns (that is, "%" and "Allineamento barre"). There is no need for an inserted value, I just need to raise an event when one of the values โ€‹โ€‹changes. How can i do this? I need a way to define an event method in which I can define some operations. I read this how to raise an event when the value in the wpf datagrid cell changes using MVVM? but I don't have an observable collection related to datagrid.

EDIT: Datagrid ItemSource is associated with the following objects:

 public class FixedPosition { [XmlAttribute] public int index { get; set; } public int percentage { get; set; } public HorizontalAlignment alignment { get; set; } } 

How can I change it to get the expected result?

thanks

+2
events wpf datagrid
source share
1 answer

You seem to view this issue from a WinForms perspective. In WPF, we usually prefer to manipulate data objects rather than user interface objects. You said that you do not have an ObservableCollection<T> for your products, but I would recommend that you use it.

If you don't have a data type class for your data, I would advise you to create one. Then you must implement the INotifyPropertyChanged interface.

After that and setting your collection property as the ItemsSource your DataGrid , all you need to do is bind the INotifyPropertyChanged handler to the selected data type:

In the view model:

 public ObservableCollection<YourDataType> Items { get { return items; } set { items = value; NotifyPropertyChanged("Items"); } } public YourDataType SelectedItem { get { return selectedItem; } set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); } } 

In the view model constructor:

 SelectedItem.PropertyChanged += SelectedItem_PropertyChanged; 

In the view model:

 private void SelectedItem_PropertyChanged(object sender, PropertyChangedEventArgs e) { // this will be called when any property value of the SelectedItem object changes if (e.PropertyName == "YourPropertyName") DoSomethingHere(); else if (e.PropertyName == "OtherPropertyName") DoSomethingElse(); } 

In the user interface:

 <DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" ... /> 
+4
source share

All Articles