在Width =“Auto”的Grid列中使用WPF MeasureOverride无限可用大小?

时间:2018-03-01 10:14:13

标签: c# wpf

我正在制作一个应该在UserControl内使用的Grid。此UserControl应具有Width所有可用空间或100,具体取决于bool。我正在尝试使用MeasureOverride中的UserControl来完成此操作。

我遇到的问题如下:当我的UserControl被放置在GridWidth="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>

0 个答案:

没有答案