Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF grid across user controls?

Tags:

wpf

grid

In ASP.NET I could make a user control to occupy more than one cell in a table on the page:

UserControl1:

<tr>
  <td>foo</td>
  <td>bar</td>
</tr>

Page1:

<table>
  <put a UserControl1 here/>
  <put another UserControl1 here/>
</table>

and the column widths adjusted automatically to fit the largest user control.

Can this be done in WPF too ? How ?

I think that user controls can't do that, and I must create a simple class instead of a user control, which has a method to add everything to the grid. But that way everything should be done by code, xaml is useless here.

like image 955
Jeno Csupor Avatar asked Sep 16 '25 00:09

Jeno Csupor


1 Answers

I've found the answer here.

It can be done with SharedSizeGroup and Grid.IsSharedSizeScope.

UserControl1.xaml:

<UserControl x:Class="WpfApplication1.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="SharedSizeGroup1"/>
            <ColumnDefinition SharedSizeGroup="SharedSizeGroup2"/>
        </Grid.ColumnDefinitions>
        <Label Name="Label1" Grid.Column="0">Label1</Label>
        <Label Name="Label2" Grid.Column="1">Label2</Label>
    </Grid>
</UserControl>

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:y="clr-namespace:WpfApplication1">
    <Grid Grid.IsSharedSizeScope="True">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <y:UserControl1 Grid.Row="0" x:Name="UserControl1A"/>
        <y:UserControl1 Grid.Row="1" x:Name="UserControl1B"/>
    </Grid>
</Window>

Window1.xaml.cs:

using System.Windows;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            UserControl1A.Label1.Content = "Label1WithLongText";
        }
    }
}
like image 84
Jeno Csupor Avatar answered Sep 17 '25 20:09

Jeno Csupor