I am creating a textbox dynamically. I have 2 columns in my grid. I want to add new textbox to the row if the other textbox value=\"tea\". I want to create new textbox to corres
Attached properties can be used to store such information so define an attached property in the class
public static int GetGridRow(DependencyObject obj)
{
return (int)obj.GetValue(GridRowProperty);
}
public static void SetGridRow(DependencyObject obj, int value)
{
obj.SetValue(GridRowProperty, value);
}
// Using a DependencyProperty as the backing store for GridRow. This enables animation, styling, binding, etc...
public static readonly DependencyProperty GridRowProperty =
DependencyProperty.RegisterAttached("GridRow", typeof(int), typeof(ViewModel), new PropertyMetadata(0));
then use it to store the value of the row
private void btn_addnew_Click(object sender, RoutedEventArgs e)
{
//1st Column TextBox
txt1 = new TextBox();
Grid.SetRow(txt1, i);
SetGridRow(text1, i);
...
grid1.Children.Add(txt1);
count++;
}
then use it when u need it
//How to set row here?
Grid.SetRow(txt2, GetGridRow(txt1));
Grid.SetColumn(txt2, 1);
If you just want to achieve this, then more elegant way will be to add the user control to your application like below:
<UserControl x:Class="WpfApplication4.TestUserControl"
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>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox Name="TextBox1"/>
<TextBox Grid.Column="1">
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=TextBox1, UpdateSourceTrigger=PropertyChanged}" Value="tea">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
</UserControl>
then in your btn_addnew_Click() method, you just need to add this usercontrol to user Grid and assign row and column to it. Showing/Hiding of textbox will be taken care of by teh user control itself.
var userControl = new MyUserControl();
userControl .Margin = new Thickness(10, 10, 0, 0);
Grid.SetRow(userControl , i);
grid1.Children.Add(userControl );
OR if you want to have value of Grid.Row for textbox1 you can get it directly as:
if (textbox1 != null)
{
int row = (int)textbox1.GetValue(Grid.RowProperty);
Grid.SetRow(txt2, row);
}