所以我得到了一個 WPF 資料網格,它是這樣創建的:
<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>
它是這樣初始化的:
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ColumnsCollection"));
itemCollectionViewSource.Source = new ObservableCollection<FormCreatorColumnInfoDatasource>();
和人口稠密。
FormCreatorColumnInfoDatasource 如下所示:
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();
}
}
}
所以現在我想在用戶手動更改列的名稱時立即更改列 WidthOfNameInCentimeter(名稱寬度)的內容,以便此列中始終存在正確的資訊。
我該怎么做呢?
uj5u.com熱心網友回復:
在@lidqy 的幫助下,我添加了一個函式并更改了名稱的設定器:
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));
}
}
不要忘記在資料源中實作 INotifyPropertyChanged 并為資料網格源使用 ObservableCollection。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/472180.html
