UWP(Universal Windows Platform)是微软推出的一个用于构建跨平台应用的框架。DataGrid
是 UWP 中用于显示和编辑数据的控件。双精度值(double
)是一种数值类型,可以表示非常大或非常小的数值,并且可以为空(null
)。
使用 DataGrid
绑定到可以为空的双精度值有以下优势:
null
值,可以更好地表示数据的完整性。null
。类型:
Nullable<double>
或简写为 double?
表示可以为空的双精度值。应用场景:
问题描述:
修改 DataGrid
单元格不会更新绑定的属性值。
原因分析:
INotifyPropertyChanged
接口,导致 UI 无法及时更新。DataGrid
的单元格编辑模板可能没有正确配置。INotifyPropertyChanged
public class MyDataModel : INotifyPropertyChanged
{
private double? _myValue;
public double? MyValue
{
get => _myValue;
set
{
if (_myValue != value)
{
_myValue = value;
OnPropertyChanged(nameof(MyValue));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
DataGrid
列在 XAML 中:
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="My Value" Binding="{Binding MyValue, Mode=TwoWay}" />
</DataGrid.Columns>
</DataGrid>
在代码后台:
public ObservableCollection<MyDataModel> DataItems { get; set; } = new ObservableCollection<MyDataModel>();
// 初始化数据
DataItems.Add(new MyDataModel { MyValue = 123.45 });
DataItems.Add(new MyDataModel { MyValue = null });
dataGrid.ItemsSource = DataItems;
完整的示例代码如下:
MyDataModel.cs:
public class MyDataModel : INotifyPropertyChanged
{
private double? _myValue;
public double? MyValue
{
get => _myValue;
set
{
if (_myValue != value)
{
_myValue = value;
OnPropertyChanged(nameof(MyValue));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainPage.xaml:
<Page
x:Class="YourNamespace.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:YourNamespace">
<Grid>
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="My Value" Binding="{Binding MyValue, Mode=TwoWay}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Page>
MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
public ObservableCollection<MyDataModel> DataItems { get; set; } = new ObservableCollection<MyDataModel>();
public MainPage()
{
this.InitializeComponent();
// 初始化数据
DataItems.Add(new MyDataModel { MyValue = 123.45 });
DataItems.Add(new MyDataModel { MyValue = null });
dataGrid.ItemsSource = DataItems;
}
}
通过以上步骤和代码示例,可以确保 DataGrid
中的双精度值在编辑后能够正确更新绑定的属性。
领取专属 10元无门槛券
手把手带您无忧上云