Filling Grid with TextBoxes programmatically in WPF

倾然丶 夕夏残阳落幕 提交于 2020-01-16 09:00:30

问题


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


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/5583954/filling-grid-with-textboxes-programmatically-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!