Как динамически добавить текстовое поле в ячейку таблицы данных и как получить введенные данные? используя Custom Usercontrol
Я разработал приложение для выставления счетов и добавил элемент управления сеткой данных в свое приложение WPF. Теперь мне нужно добавить текстовое поле в ячейку таблицы данных программно.
Можете ли вы дать мне некоторое представление о том, как найти текстовое поле внутри CellEditingTemplate? Пожалуйста, обратитесь этот скриншот - заранее спасибо
введите описание изображения здесь
UserControltest.xaml
<UserControl x:Class="InvoiceApp.UserControltest" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="ItemHolder" Height="30">
</Grid>
</UserControl>
**Mainwindow(FrmBill.xmal):**
<Window x:Class="InvoiceApp.FrmBill"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Testgrid" Height="300" Width="400" Loaded="Window_Loaded">
<Grid>
<VirtualizingStackPanel x:Name="MydataGrid" VerticalAlignment="Stretch" Height="350"/>
<!--Now here i am setting the height to 0,the reason will be explained afterwards-->
</Grid>
</Window>
FrmBill.cs (код C#):
string str = ConfigurationManager.AppSettings["ConnectInvoice"].ToString();
SqlConnection con;
public FrmBill()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
con = new SqlConnection(str);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_Tax", con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
UserControltest row = new UserControltest();
int trd = row.ItemHolder.ColumnDefinitions.Count;
if(row.ItemHolder.ColumnDefinitions.Count==0)
{
row.ItemHolder.ColumnDefinitions.Add(new ColumnDefinition());//this will ad required number of columns which will represent the cells
}
TextBox txtbx = new TextBox();
txtbx.Height = 20;
row.ItemHolder.Children.Add(txtbx);
Grid.SetColumn(txtbx,3); /// here 1 is the column count, change it as you want :)
MydataGrid.Children.Add(row);
MydataGrid.Height = MydataGrid.Height + 30;
}
}
1 ответ
Как упоминалось в ОП, он хочет пойти с обычаем User-control
вот XAML для образца User-Control
это может представлять Data-Row
,
<UserControl x:Class="MyDatarow"
......>
<Grid x:Name="ItemHolder" Height="30" x:FieldModifier ="Public">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20*" /> <!--Create as many column as you want during design time,or you can simply create it dynamically -->
<ColumnDefinition Width="20*" /><!--Now here i am setting the Width to 20*,instead of this you can set a MinWidth and MaxWidth if you want , i recommend it too-->
<ColumnDefinition Width="20*" />
<!--When i write the c# code,i will consider that no column were added here during design time-->
</Grid.ColumnDefinitions>
Теперь давайте представим это как DataGrid
Предположим, что данные поступают из базы данных, тогда мы можем использовать IDataReader
а также VirtualizingStackPanel
достичь datagrid
смотреть:
<VirtualizingStackPanel x:Name="MydataGrid" VerticalAlignment="Stretch" Height="0"/> <!--Now here i am setting the height to 0,the reason will be explained afterwards-->
C#
SqlConection con=new SqlConnection("connection string here")
SqlCommand cmd = new SqlCommand("Select * from table",con)
SqlDatareader dr = cmd.ExecuteReader();
While (dr.Read())
{
MyDatarow row = new MyDatarow;
If (row.ItemHolder.ColumnDefinition.Count = 0)
{
row.ItemHolder.ColumnDefinition.Add(new ColumnDefinition)//this will ad required number of columns which will represent the cells
}
TextBox txtbx = new TextBox;
txtbx.Height = 20
row.ItemHolder.Children.Add(txtbx)
Grid.SetColumn(txtbx,1) /// here 1 is the column count, change it as you want :)
MyDatagrid.Childer.Add(row);
MyDatagrid.height = MyDatagrid.height + 30 ;
}
Надеюсь, это решит вашу проблему:)