【发布时间】:2014-01-24 19:21:54
【问题描述】:
我创建了一个 WPF 自定义控件,我把它放在一个表单上,并给它一个高度和一个宽度 - 一切正常。我在控件中使用 TemplateBinding 引用高度和宽度,所以我需要设置这些。
如果我决定使用 gui 调整控件的大小,高度和宽度完全消失并且控件格式出错。
发生这种情况时如何获取控件的新高度和宽度并进行设置?
按要求发布代码:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GraphControls">
<Style TargetType="{x:Type local:ContourPlot}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ContourPlot}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Viewbox>
<Border BorderBrush="Black" BorderThickness="1">
<Canvas x:Name="cvGraph" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" >
<Rectangle Canvas.Left="40" Canvas.Top="31" Width="48" Height="41" Fill="AliceBlue"/>
</Canvas>
</Border>
</Viewbox>
<Canvas Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" >
<Label x:Name="lblTest" Canvas.Left="0" Canvas.Top="10" Content="Label" FontSize="12" />
</Canvas>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
控件的使用形式如下:
<Window x:Class="GraphWrapper.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gc="clr-namespace:GraphControls;assembly=GraphControls"
Title="MainWindow" Height="350" Width="525">
<Grid>
<gc:ContourPlot Background="#FFC3EAC3" Margin="65,42,128,118" Width="310" Height="150"/>
</Grid>
</Window>
如前所述,当通过 gui 调整控件大小时,Width 和 Height 属性消失。
【问题讨论】:
-
发布你到目前为止尝试过的代码..
标签: wpf custom-controls