我正在制作一个应该在UserControl
内使用的Grid
。此UserControl
应具有Width
所有可用空间或100
,具体取决于bool
。我正在尝试使用MeasureOverride
中的UserControl
来完成此操作。
我遇到的问题如下:当我的UserControl
被放置在Grid
列Width="Auto"
内时,我得到的Size
可用了Infinite
Width
。
我预计Width
本身Grid
,减去任何其他固定Column
Width
等。
示例代码:
Usercontrol XAML:
<UserControl x:Class="WpfApp1.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"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Text="Custom UserControl content" />
</Grid>
</UserControl>
UserControl codebehind:
using System.Windows;
namespace WpfApp1
{
public partial class UserControl1
{
public static readonly DependencyProperty ExpandProperty = DependencyProperty.Register(nameof(Expand), typeof(bool), typeof(UserControl1),
new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.AffectsMeasure));
public bool Expand
{
get => (bool)GetValue(ExpandProperty);
set => SetValue(ExpandProperty, value);
}
public UserControl1()
{
InitializeComponent();
}
protected override Size MeasureOverride(Size constraint)
{
if (Expand)
{
//constraint.Width is infinite, creates exception
return constraint;
}
return new Size(100, constraint.Height);
}
}
}
主窗口XAML:
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="200"/>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid Background="Beige" Grid.Column="0">
<CheckBox IsChecked="{Binding ElementName=MyControl,Path=Expand}" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="Expand MyControl"/>
</CheckBox>
</Grid>
<wpfApp1:UserControl1 Grid.Column="1" x:Name="MyControl" Background="CornflowerBlue"/>
</Grid>
有没有可行的方法来实现我想要的?或者我应该尝试以不同的方式处理它?</ strong>