Filling Grid with TextBoxes programmatically in WP

2019-08-22 00:31发布

Let's assume that I have defined two Grids and few TextBoxes in my XAML. I want to put these TextBoxes in the Grids at runtime (I know which TextBox should be put in which Grid after starting the application).

I thought it would be possible to simply add a row definition to the Grid in my C# code, however the text boxes bind to some Style.

Maybe there is a simple solution (entirely in XAML - preferred)?

So the question is - how to dynamically fill the grid during the runtime with the items (text boxes) and the grid defined in XAML? Both items bind to some styles etc.

Thanks in advance for the replies and hints!

Cheers

3条回答
一夜七次
2楼-- · 2019-08-22 00:58

I don't fully get you question, but if I understood correctly you want TextBoxes inside your grid using XAML.

If this is the case

you can do:

 <GridViewColumn CellTemplate="{StaticResource editColumnTemplate}"/>

and then in a static resource:

 <DataTemplate x:Key="editColumnTemplate">
            <TextBox Text="{Binding Path=DataContext.Foo}" />
 </DataTemplate>

HTH

查看更多
The star\"
3楼-- · 2019-08-22 01:06

Ok, so I am giving it a shot:

Grid uiElement = (Grid)txt1.Parent;

        if (uiElement.Children.Contains(txt1))
            uiElement.Children.Remove(txt1);

        txt1.Margin = new Thickness(0);

        Grid.SetRow(txt1, 3);
        Grid.SetColumn(txt1, 2);
        grid.Children.Add(txt1);

This is in code behind (TextBox).

You would obviously have to configure your code but this is the basic example.

You first have to remove to TextBox From it's parent control (Code makes the assumption that it's a grid).

And then you have to set the margin to 0 (or something else given that chances are if it's in a parent grid the margins might be big which will cause the control to be off screen).

Then set the controls column as well as row and then add the control to the new grid.

EDIT: Let me know if you want to customize it so that it loops through a grid and removes all the textboxes from that grid into another grid

查看更多
地球回转人心会变
4楼-- · 2019-08-22 01:07

Maybe you can achieve the result you desire by using ItemsControl.

查看更多
登录 后发表回答