我在 WPF 中创建了一个带有可编辑单元格的简单 DataGrid。但我从编辑的单元格中获取空数据。我是WPF的新手。问题是什么?
当我尝试更改文件夹单元格时,它已更改,如图 所示。
这就是结果!
守则,
namespace MyApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Product> tmpProducts = new List<Product>();
tmpProducts.Add(new Product {
id = 1, title = "Product A", folder = null,
});
tmpProducts.Add(new Product {
id = 2, title = "Product B", folder = null,
});
productGrid.ItemsSource = tmpProducts;
}
private void selectFolder(object sender, RoutedEventArgs e)
{
// selected folder from dialog, etc. then,
string selectedPath = "C:\\myFolder";
object item = productGrid.SelectedItem;
(productGrid.SelectedCells[2].Column.GetCellContent(item) as TextBlock).Text = selectedPath;
}
private void updateProducts(object sender, RoutedEventArgs e)
{
for (int i = 0; i < productGrid.Items.Count; i++)
{
Product prd = (Product)productGrid.Items[i];
Console.WriteLine(prd.folder);
}
}
}
class Product
{
public int id { get; set; }
public string title { get; set; }
public string folder { get; set; }
}
}
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="productGrid" AutoGenerateColumns="False" CanUserAddRows="False" Margin="0,0,0,36">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding id}" Header="ID"/>
<DataGridTextColumn Binding="{Binding title}" Header="Title" Width="*"/>
<DataGridTextColumn Binding="{Binding folder}" Header="Foler" Width="*"/>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="selectFolder" Content="Browse.." Width="100"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button Click="updateProducts" Content="Save" HorizontalAlignment="Left" Margin="432,289,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>