WPF UserControl 设计时间大小

标签 wpf user-controls autosize

在 WPF 中创建 UserControl 时,我发现给它一些任意的高度和宽度值很方便,以便我可以在 Visual Studio 设计器中查看我的更改。但是,当我运行该控件时,我希望高度和宽度未定义,以便控件将展开以填充我放置它的任何容器。如何实现相同的功能,而不必先删除高度和宽度值建立我的控制权? (或者不在父容器中使用 DockPanel。)

以下代码演示了该问题:

<Window x:Class="ExampleApplication3.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:loc="clr-namespace:ExampleApplication3"
    Title="Example" Height="600" Width="600">
    <Grid Background="LightGray">
        <loc:UserControl1 />
    </Grid>
</Window>

UserControl1 的以下定义在设计时合理显示,但在运行时显示为固定大小:

<UserControl x:Class="ExampleApplication3.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <Grid Background="LightCyan" />
</UserControl>

以下 UserControl1 定义在设计时显示为点,但在运行时扩展以填充父 Window1:

<UserControl x:Class="ExampleApplication3.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="LightCyan" />
</UserControl>

最佳答案

对于 Blend,一个鲜为人知的技巧是将这些属性添加到您的用户控件或窗口:

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"
       d:DesignHeight="500" d:DesignWidth="600"

这会将设计高度和宽度分别设置为 500 和 600。然而,这仅适用于混合设计师。不是 Visual Studio 设计器。

就 Visual Studio 设计器而言,您的技术就是有效的。这就是为什么我不使用 Visual Studio Designer。 ;)

关于WPF UserControl 设计时间大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75495/

相关文章:

asp.net - 嵌套用户控件的控件为空

c# - 循环访问 UserControl 的控件

android - 自动调整 EditText

ios - 如何使 UICollectionView 通过自动调整大小来填充其 super View ?

iphone - 在代码中自动调整 UIImageView 的大小

wpf - Visual Studio 2010 - 字典未找到但存在

wpf - 将 FixedDocument 保存到 XPS 文件会导致内存泄漏

wpf - 如何在 WPF 中从 XAML 调用调用方法?

c# - 更改显示 (UI)/项目 Observable 集合的顺序

c# - 以编程方式在 ASP.NET 中添加用户控件