我正在开发一个WPF应用程序来练习MVVM。我需要有4个网格,都只有两列-一个用于“显示”控件(带有字段名称的TextBlock/RadioButton),另一个用于“值”控件(表示字段值所需的任何控件)。
每个网格在另一个用户控件中,我需要让它们的所有第一列保持同步,这样“值”控件将在屏幕上伸展,而“显示”控件将具有不变的自动宽度。
如果我用常量名称设置SharedSizeColumn,所有的网格都是完美且美观的同步,但我需要通过绑定视图模型来设置SharedSizeColumn,因为包含这些网格的一些用户控件在选项卡式视图模型之间共享,以便重用,并且跨选项卡/视图模型,我不希望网格同步。当我使用绑定设置SharedSizeGroup时,所有网格中的2列就好像根本没有设置SharedSizeGroup一样,我甚至尝试过使用BindingOperations通过代码设置绑定,但仍然没有成功。
你知道如何成功绑定SharedSizeGroup,或者防止SharedSizeGroup在重用相同用户控件的选项卡之间共享的另一种解决方案吗?
发布于 2011-06-25 09:58:01
下面是将SharedSizeGroup与数据绑定一起使用的完整工作示例。
标记:
<Grid>
<StackPanel Grid.IsSharedSizeScope="True" Margin="20">
<Grid HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="{Binding ColumnA}"/>
<ColumnDefinition SharedSizeGroup="{Binding ColumnB}"/>
</Grid.ColumnDefinitions>
<TextBlock Text="aa" Grid.Column="0" Foreground="Red"/>
<TextBlock Text="bbbbbbbb" Grid.Column="1" Foreground="Blue"/>
</Grid>
<Grid HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="{Binding ColumnC}"/>
<ColumnDefinition SharedSizeGroup="{Binding ColumnD}"/>
</Grid.ColumnDefinitions>
<TextBlock Text="cccccccc" Grid.Column="0" Foreground="Red"/>
<TextBlock Text="dd" Grid.Column="1" Foreground="Blue"/>
</Grid>
</StackPanel>
</Grid>和代码隐藏:
void Window_Loaded(object sender, RoutedEventArgs e)
{
DataContext = new SharedSizeGroupViewModel
{
ColumnA = "group1",
ColumnB = "group2",
ColumnC = "group1",
ColumnD = "group2",
};
}和原始视图模型:
public class SharedSizeGroupViewModel
{
public string ColumnA { get; set; }
public string ColumnB { get; set; }
public string ColumnC { get; set; }
public string ColumnD { get; set; }
}它看起来是这样的:

它显示了红色和蓝色的列排列在一起。
https://stackoverflow.com/questions/6474125
复制相似问题