【发布时间】:2020-09-08 04:30:56
【问题描述】:
我有一个派生自Windows.Controls.Control 的类Tableau,它的模板包含一个Canvas:
<Style TargetType="{x:Type local:Tableau}">
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Tableau}">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ScrollViewer x:Name="ScrollViewer"
HorizontalScrollBarVisibility="{Binding RelativeSource={RelativeSource TemplatedParent},Path=HorizontalScrollBarVisibility}"
VerticalScrollBarVisibility="{Binding RelativeSource={RelativeSource TemplatedParent},Path=VerticalScrollBarVisibility}"
>
<Canvas x:Name="Diagram"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}"
>
<Canvas.RenderTransform>
<ScaleTransform CenterX="0"
CenterY="0"
ScaleX="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Scale}"
ScaleY="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Scale}"
/>
</Canvas.RenderTransform>
</Canvas>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
和Tableau 类是:
public class Tableau:Control
{
private Canvas _canvas;
public Canvas Canvas
{
get { return _canvas; }
}
static Tableau()
{
FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(
typeof(Tableau), new FrameworkPropertyMetadata(typeof(Tableau)));
}
public Tableau()
: base()
{
this.Loaded += Tableau_Loaded;
}
private void Tableau_Loaded(object sender, RoutedEventArgs e)
{
_canvas = (Canvas)this.Template.FindName("Diagram", this);
}
}
我想把它用作画布,像这样:
<local:Tableau>
<Rectangle Fill="AliceBlue" Stroke="Black" Width="100" Height="100" Canvas.Top="10"/>
<Rectangle Fill="AliceBlue" Stroke="Black" Width="100" Height="100" Canvas.Left="130" Canvas.Top="50"/>
</local:Tableau>
有没有可能,如果有怎么办?
【问题讨论】:
-
您可以从 ItemsControl 派生,并通过 Style 设置 ItemsPanel 属性。
-
如果您已经看到我的答案,我只是做了更多的测试并更新了它。现在应该是更完整的解决方案了。
标签: c# wpf templates canvas controls