So I got a WPF datagrid which is created like this:
<DataGrid x:Name="columns" Grid.Row="1" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" ItemsSource="{Binding}" DataContext="{StaticResource ColumnsCollection}"
AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" AddingNewItem="columns_AddingNewItem">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="Auto"/>
<DataGridTextColumn Header="Width of Name" Binding="{Binding WidthOfNameInCentimeter}" Width="Auto"/>
</DataGrid.Columns>
</DataGrid>
it is initialized like this:
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ColumnsCollection"));
itemCollectionViewSource.Source = new ObservableCollection<FormCreatorColumnInfoDatasource>();
and populated.
The FormCreatorColumnInfoDatasource looks like this:
class FormCreatorColumnInfoDatasource : INotifyPropertyChanged
{
private IFormCreatorColumnInfo m_info;
public string Name
{
get
{
return m_info.Name;
}
set
{
m_info.Name = value;
}
}
public string WidthOfNameInCentimeter
{
get
{
var exactWidthInCentimeter = Name.Length * 0.238M;
var roundedUpToHalfCentimeter = Math.Round(exactWidthInCentimeter * 2, MidpointRounding.AwayFromZero) / 2;
return (roundedUpToHalfCentimeter).ToString();
}
}
}
So now I want to instantly change the content of the column WidthOfNameInCentimeter (Width of Name) when the user manually changes the Name of the column so there is always the correct information in this column.
How do I do this?
CodePudding user response:
With the help of @lidqy I added a function and changed the setter of Name:
class FormCreatorColumnInfoDatasource : INotifyPropertyChanged
{
private IFormCreatorColumnInfo m_info;
public string Name
{
get
{
return m_info.Name;
}
set
{
m_info.Name = value;
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(WidthOfNameInCentimeter));
}
}
public string WidthOfNameInCentimeter
{
get
{
var exactWidthInCentimeter = Name.Length * 0.238M;
var roundedUpToHalfCentimeter = Math.Round(exactWidthInCentimeter * 2, MidpointRounding.AwayFromZero) / 2;
return (roundedUpToHalfCentimeter).ToString();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
Dont forget to implement INotifyPropertyChanged in the datasource and to use an ObservableCollection for the datagrids source.