Generic.xaml中忽略UserControl的显式属性

时间:2015-06-02 10:56:02

标签: wpf

我有一个简单的UserControl,默认宽度和高度在UserControl1.xaml中指定:

<UserControl x:Class="WpfApplication7.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         Width="100" Height="100"
         d:DesignHeight="300" d:DesignWidth="300">

    <Border Background="Blue"/>
</UserControl>

然后我将此UserControl放在自定义控件CustomControl1中,并覆盖Generic.xaml中的Width和Height值:

<Style TargetType="{x:Type local:CustomControl1}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                <local:UserControl1 Width="5" Height="5" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

由于某种原因,当我实例化我的CustomControl1时,我看到忽略了Width和Height的指定值。

Screenshot

现在,我找到了解决此问题的方法。

但我想明白为什么会这样?

2 个答案:

答案 0 :(得分:1)

从自定义控件中删除固定的宽度和高度。

Marker

在主视图中设置宽度和高度时应该有效。

答案 1 :(得分:1)

这是因为您在UserControl上硬编码的高度/宽度为100 x 100 - 并且这些值的优先级高于您在CustomControl的CustomControl实例中设置高度/宽度为5 x 5时的优先级。 UserControl。

即使您为自定义控件定义高度/宽度(例如5 x 5) - 它实际上也不会改变用户控件的大小,它只会显示5 x 5的部分。当然,这最好用图像而不是矩形来说明。