我的答案来自
ms connect
:
通常,您可以通过不使用SharedSizeGroup来解决此问题,而是将所有共享大小绑定到一个对象(例如,您的DataContext)上的单个属性:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication3"
Height="350" Width="525" Title="MainWindow">
<Window.DataContext>
<my:MainWindowData Width0="1*" Width1="1*" />
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="dt">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding Path=Width0, Mode=TwoWay}" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="{Binding Path=Width1, Mode=TwoWay}" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="{Binding Width0}" />
<GridSplitter Grid.Column="1" Width="10" ResizeBehavior="PreviousAndNext" ResizeDirection="Columns" />
<Button Grid.Column="2" Content="{Binding Width1}" />
</Grid>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource dt}" />
<ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource dt}" />
</StackPanel>
</Window>
其中width0和width1是匹配类型(gridlength)。它可以与任何类型的大小(固定、星型和自动)结合使用。
更新
:
或者,也许更好,您可以完全在XAML中进行,而不是绑定到DataContext。只需定义一个带有命名列的主网格(不一定是父网格,但需要某种方法来引用它),然后按名称绑定到它们。
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350" Width="525" Title="MainWindow">
<!-- shared sizing used only on fixed size columns therefore safe -->
<!-- alternatively you can hardcode width of splitter column -->
<Grid Name="masterGrid" Grid.IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" Name="masterColumn0" />
<ColumnDefinition Width="Auto" SharedSizeGroup="masterColumn1" />
<ColumnDefinition Width="1*" Name="masterColumn2" />
</Grid.ColumnDefinitions>
<StackPanel Grid.ColumnSpan="3">
<StackPanel.Resources>
<DataTemplate x:Key="dt">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding Path=Width, Mode=TwoWay, ElementName=masterColumn0}" />
<ColumnDefinition Width="Auto" SharedSizeGroup="masterColumn1" />
<ColumnDefinition Width="{Binding Path=Width, Mode=TwoWay, ElementName=masterColumn2}" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="{Binding Path=Width, Mode=TwoWay, ElementName=masterColumn0}" />
<Button Grid.Column="2" Content="{Binding Path=Width, Mode=TwoWay, ElementName=masterColumn2}" />
</Grid>
</DataTemplate>
</StackPanel.Resources>
<ContentPresenter ContentTemplate="{StaticResource dt}" />
<ContentPresenter ContentTemplate="{StaticResource dt}" />
</StackPanel>
<GridSplitter Grid.Column="1" Width="10" ResizeBehavior="PreviousAndNext" ResizeDirection="Columns" ShowsPreview="True" />
</Grid>
</Window>
这增加了使用所有网格共享的单个网格拆分器的好处。