当在wpf中显式设置宽度和高度时,如何为我的自定义控件提供大小调整支持



即使我明确设置了宽度和高度,我也希望在调整主窗口大小时,为我的自定义控件提供调整大小的行为。我该怎么做?

这里只是简单的代码。像这样我的自定义控件。

<Border Background="Red" Width="300" Height="300" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="15"/>

任何人请向我提供你的建议。

只需不显式地为该控件提供任何Height和Width。并将其放置在具有高度为*的RowDefinition和宽度为*的ColumnDefinition的窗口网格中。

用户控制

<UserControl x:Class="debuggingusingreflector.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" 
         >
<Grid>
    <TextBox  Background="Gray"/>
</Grid>

窗口.xaml

<Window x:Class="debuggingusingreflector.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:x1="clr-namespace:debuggingusingreflector"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TextBox Height="100" Text="{Binding Name}" Background="Red"/>
    <x1:UserControl1 Grid.Row="1"/>
</Grid>

我希望这会有所帮助。

您可以在运行时通过代码影响Width/Height属性。当调整主窗体的大小时,执行这些操作也没有问题。样品:

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" SizeChanged="Window_resize">
    <Grid>
        <Border Background="Red" Width="300" Height="300" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="15" Name="borderName" />
    </Grid>
</Window>

CS-

 private void Window_resize(Object sender, SizeChangedEventArgs e)
 {
     borderName.Width = 0.5 * this.Width;
     borderName.Height = 0.5 * this.Height;
 }

最新更新