這將是非常困難的,因爲usercontrol中的所有內容都僅由該usercontrol呈現。擁有usercontrol的網格對usercontrol的內容一無所知,我認爲它應該保持這種方式。但是,您可以使用前綴,文本和前綴寬度依賴屬性創建自定義控件。
例子:
public class PrefixRow: Control
{
static PrefixRow()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PrefixRow) , new FrameworkPropertyMetadata(typeof(PrefixRow)));
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty , value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text" , typeof(string) , typeof(PrefixRow) , null);
public double PrefixWidth
{
get { return (double)GetValue(PrefixWidthProperty); }
set { SetValue(PrefixWidthProperty , value); }
}
public static readonly DependencyProperty PrefixWidthProperty =
DependencyProperty.Register("PrefixWidth" , typeof(double) , typeof(PrefixRow) , null);
public string Prefix
{
get { return (string)GetValue(PrefixProperty); }
set { SetValue(PrefixProperty , value); }
}
public static readonly DependencyProperty PrefixProperty =
DependencyProperty.Register("Prefix" , typeof(string) , typeof(PrefixRow) , null);
}
在窗口:
<Window x:Class="WPFApp.GridWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="GridWindow" Height="300" Width="300" xmlns:local="clr-namespace:WPFApp"
>
<Window.Resources>
<Style TargetType="{x:Type local:PrefixRow}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:PrefixRow}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{TemplateBinding Prefix}" Grid.Column="0" Width="{TemplateBinding PrefixWidth}"
VerticalAlignment="Center"/>
<TextBox Text="{TemplateBinding Text}" Grid.Column="1"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<local:PrefixRow PrefixWidth="{Binding ElementName=ColumnSlider, Path=Value}" Prefix="Row1" VerticalAlignment="Top" Text="test" Grid.Row="0"/>
<local:PrefixRow PrefixWidth="{Binding ElementName=ColumnSlider, Path=Value}" Prefix="Row1" VerticalAlignment="Top" Text="test" Grid.Row="1"/>
<local:PrefixRow PrefixWidth="{Binding ElementName=ColumnSlider, Path=Value}" Prefix="Row1" VerticalAlignment="Top" Text="test" Grid.Row="2"/>
<local:PrefixRow PrefixWidth="{Binding ElementName=ColumnSlider, Path=Value}" Prefix="Row1" VerticalAlignment="Top" Text="test" Grid.Row="3"/>
<Slider x:Name="ColumnSlider" Minimum="10" Maximum="300" Value="50" Grid.Row="4"/>
</Grid>
這正是我所要求的。謝謝!! – 2012-03-14 11:13:56