I have a WPF application, in which I use Entity Framework .
The collection that is bound to the DataGrid
is a collection of auto generated classes of the table generated by Entity Framework .
Model
(auto-generated by Entity Framework)
public partial class tblTest
{
public tblTest()
{
}
public int TestId{get;set;}
public string TestName {get;set;}
public string UpdatedBy {get;set;}
}
ViewModel
private ObservableCollection<tblTest> _objTest;
public ObservableCollection<tblTest> TestList
{
get { return _objTest; }
set { _objTest; = value;}
}
XAML
<DataGrid Name="grdTest" ItemSource="{Binding Path=TestList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}
AutoGenerateColumns="False" CanUserAddRows="True">
<Datagrid.Columns>
<DataGridTextColumn Width="140">
<DataGridTextColumn.Binding>
<Binding Path="TestName" Mode="TwoWay" >
<Binding.ValidationRules>
<localVal:ValidationRules/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.Header>
<TextBlock Width="128" Text="Test Name" ToolTip="Enter name"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Width="140">
<DataGridTextColumn.Binding>
<Binding Path="UpdatedBy" Mode="TwoWay" >
<Binding.ValidationRules>
<localVal:ValidationRules/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.Header>
<TextBlock Width="128" Text="Updated By" ToolTip="Name of the user that updated the record"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</Datagrid.Columns>
</DataGrid>
I allow the user to add new rows in the DataGrid
, when a new empty row is added in the DataGrid
I want the UpdatedBy
column to be auto generated by the current user credentials (and it is made readonly ).
Is there a way to extend the model class of the test table to write a constructor to take current user details as updated by. Or is there a different approach for this?
Yes you can do this by adding a new part to the auto-generated class, typically in a new file:
public partial class tblTest
{
public tblTest(string updatedBy)
{
this.UpdatedBy = updatedBy;
}
}
The secret is the partial
keyword that instructs the compiler that the whole class can be split into more than one source file.
EDIT: you can handle the AddingNewItem
event to do what you want:
In the XAML:
<DataGrid ... AddingNewItem="DataGrid_AddingNewItem" ...>
...
<DataGridTextColumn Width="140" IsReadOnly="True">
In the code behind:
private void DataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
{
e.NewItem = new tblTest { UpdatedBy = Environment.UserName };
}
It will be triggered each time the user is willing to add a new item, by entering edit mode of the last empty row.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.