0

I am trying to dynamically create a textbox and a button in a listview and that works fine. Next thing iam trying is to get the text present in the dynamically created textbox and display as a content of a button on a button_click event.I am confused and don`t know how to access the dynamicaaly created button or text in the code behind as "name property" is not valid for the same.

Any suggestion are welcomed......

XAML

<ListView Height="222" HorizontalAlignment="Left" Margin="341,24,0,0" Name="listView1" VerticalAlignment="Top" Width="290" Background="Green" 
              AllowDrop="True" 
              DragDrop.Drop="listview_drop" 
              DragDrop.DragEnter="treeview_dragenter" ItemsSource="{Binding XPath=self::*}"></pre>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" x:Name="stc">
                    <TextBlock Text="{Binding Path=Name}" Margin="0,0,3,0"/>
                    <ComboBox Margin="0,0,3,0" x:Name="cbox1">
                        <ComboBoxItem Content="Less Than"/>
                        <ComboBoxItem Content="Greater Than"/>
                        <ComboBoxItem Content="Equals"/>
                    </ComboBox>
                    <TextBox Margin="0,0,3,0" Width="50" x:Name="textbox1" />
                    <Button x:Name="but1" Height="25" Width="35" Click="click" Content="gen" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Code

private void click(object sender, RoutedEventArgs e)
{
    //Don`t know what do do here           
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
Abhinav
  • 75
  • 1
  • 1
  • 11

2 Answers2

1

You may get the named TextBox by means of the FindName method:

private void click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    var parent = button.Parent as FrameworkElement;
    var textBox = parent.FindName("textbox1") as TextBox;
    button.Content = textBox.Text;
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
0

In your click event handler, the sender parameter will be the Button that was clicked. So if you cast it to Button, you get the button object to play with.

But that just gets you the button. If you then get hold of the Button's DataContext, that is the object which the DataTemplate the button is part of was created to display.

Usually at this point I would have associated the text of the things in the template with the DataContext object via data binding, so then it's just a case of manipulating the DataContext object appropriately and the UI will update automatically.

If you haven't done that, then from the Button you can go up the WPF visual tree and start hunting for the other controls in the template, but while that is possible it's usually more hassle than its worth when you can just use databinding.

Matthew Walton
  • 9,809
  • 3
  • 27
  • 36