我尝试创建一个WPF自定义控件,该控件将TextBox
与两个按钮结合在一起。对于布局,我使用的网格是第一列的TextBox
和最后两列的按钮。
现在,我想使最后两列变成正方形-但我不知道如何到达那里。我的XAML看起来像这样:
<UserControl x:Class="Demo.Wpf.Controls.ConfirmationButton"
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"
xmlns:local="clr-namespace:Demo.Wpf.Controls"
mc:Ignorable="d"
d:DesignHeight="28.341" d:DesignWidth="226.904">
<Border BorderBrush="Black" BorderThickness="1">
<Grid ShowGridLines="True" x:Name="layoutGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="{Binding ActualHeight, ElementName=myRow, Mode=OneWay}"/>
<ColumnDefinition Width="{Binding ActualHeight, ElementName=myRow, Mode=OneWay}"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition x:Name="myRow" />
</Grid.RowDefinitions>
<Rectangle Fill="Red" Grid.Row="0" Grid.Column="0"></Rectangle>
<Rectangle Fill="Green" Grid.Row="0" Grid.Column="1"></Rectangle>
<Rectangle Fill="Blue" Grid.Row="0" Grid.Column="2"></Rectangle>
</Grid>
</Border>
</UserControl>
但是网格看起来仍然像这样:
那么我在这里做错了什么?有想法吗?
答案 0 :(得分:1)
我通过绑定到矩形本身的高度来使它起作用,只要看一下即可:
<Rectangle Name="rect1" Fill="Green" Grid.Row="0" Grid.Column="1" Width="{Binding ElementName=rect1, Path=ActualHeight}"></Rectangle>
<Rectangle Name="rect2" Fill="Blue" Grid.Row="0" Grid.Column="2" Width="{Binding ElementName=rect2, Path=ActualHeight}"></Rectangle>
答案 1 :(得分:1)
为了透明起见,我不建议像Ian所建议的那样在控件级别上设置布局大小。从长远来看,这将使适应它变得更加困难。
因此,这是我的解决方案,将ColumnDefinition
的宽度绑定到网格的ActualHeight
。另外,如果可以避免,我不建议将名称用于绑定目的。具有名称的控件将始终保持加载状态,即使它不可见或超出范围!
<Border BorderBrush="Black" BorderThickness="1">
<Grid ShowGridLines="True" x:Name="layoutGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource AncestorType=Grid}, Mode=OneWay}"/>
<ColumnDefinition Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource AncestorType=Grid}, Mode=OneWay}"/>
</Grid.ColumnDefinitions>
<Rectangle Fill="Red" Grid.Row="0" Grid.Column="0"></Rectangle>
<Rectangle Fill="Green" Grid.Row="0" Grid.Column="1"></Rectangle>
<Rectangle Fill="Blue" Grid.Row="0" Grid.Column="2"></Rectangle>
</Grid>
</Border>