I'd like to add my custom control into a template column of data grid.
The custom control is very similar to a text box, but has an icon in it. The user can click the icon, and selects an item from a prompted window, then the selected item will be filled into the text box.
My problem is when the text box is filled, after I click the second column, the text will disappear. If I replace the custom control with a simple text box, the result is the same.
Here is the sample code:
//Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleGridTest
{
public class Employee
{
public string Department { get; set; }
public int ID { get; set; }
public string Name { get; set; }
}
}
Mainwindow.xaml
<Window x:Class="SimpleGridTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="grid" Grid.Row="1" Margin="5" AutoGenerateColumns="False"
RowHeight="25" RowHeaderWidth="10"
ItemsSource="{Binding}"
CanUserAddRows="True" CanUserSortColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Department" Width="150">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Department}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"
Width="100"/>
<DataGridTextColumn Header="Name"
Binding="{Binding Path=Name}"
Width="200"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Collections.ObjectModel;
namespace SimpleGridTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<Employee> _employees = new ObservableCollection<Employee>();
public ObservableCollection<Employee> Employees
{
get { return _employees; }
set { _employees = value; }
}
public MainWindow()
{
InitializeComponent();
grid.ItemsSource = Employees;
}
}
}
How can I fix this problem? Or I need to write a DataGrid***Column as DataGridTextColumn? Thanks in advance!
Best Regards,
Johnson
I guess you have to specify a CellEditingTemplate for editing and to display content you have to specify a normal celltemplate
<Controls:DataGridTemplateColumn Header="Department" Width="150">
<Controls:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Department}" />
</DataTemplate>
</Controls:DataGridTemplateColumn.CellTemplate>
<Controls:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Department}"/>
</DataTemplate>
</Controls:DataGridTemplateColumn.CellEditingTemplate>
</Controls:DataGridTemplateColumn>
Hope this helps..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With