水平拉伸元素的绑定宽度属性

Bind Width property of elements which are horizontally stretched

我在网格的一列中有一个分组框和网格拆分器控件。组框的水平对齐设置为拉伸,因此当我拖动拆分器时它会占据所有 space。一切正常。

现在我需要将组框的值存储在绑定对象的属性中,但是一旦我绑定宽度属性,它就会卡住,它不再在拉伸拆分器时自行拉伸。

我知道原因,因为现在绑定属性负责其宽度,并且不会更改。但不知道如何让它发挥作用。这是我的 XAML.

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Grid x:Name="InnerGrid" HorizontalAlignment="Stretch" Height="{Binding ElementName=Control1,Path=ActualHeight}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" MinWidth="200"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <GroupBox Header="{Binding TrackName}" VerticalAlignment="Stretch" Margin="3 0 3 0" HorizontalAlignment="Stretch" />
            <GridSplitter Width="5" VerticalAlignment="Stretch" Focusable="False" Background="Gray"/>
        </Grid>
    </DataTemplate>
</ItemsControl.ItemTemplate>

据我了解,您需要阅读 GroupBox 的计算宽度。为此,您可以使用 ActualWidth 属性。

编辑: 您可以编写自定义 GroupBox 并使用依赖属性:

public class MyGroupBox : GroupBox
{
    public static readonly DependencyProperty CurrentWidthProperty =
        DependencyProperty.Register("CurrentWidth", typeof(double),
        typeof(MyGroupBox), new FrameworkPropertyMetadata(0d));

    public double CurrentWidth
    {
        get { return this.ActualWidth; }
        set { SetValue(CurrentWidthProperty, value); }
    }
}

XAML:

<Window x:Class="FunWithWpfAndXP.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:FunWithWp"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" MinWidth="200"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <local:MyGroupBox CurrentWidth="{Binding Path=myProp}" VerticalAlignment="Stretch" Margin="3 0 3 0" HorizontalAlignment="Stretch"/>
        <GridSplitter Width="5"  VerticalAlignment="Stretch"  Focusable="False" Background="Gray"/>
    </Grid>
</Window>

也许您真的对绑定 ColumnDefinition 宽度感兴趣,因此:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="{Binding Width}" MinWidth="200"/>
    <ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>

问题是您的绑定正在重置 GridSplitter 更改的宽度,将 GroupBox Width 绑定的 Mode 设置为 OneWayToSource应该(可能)帮助你,你可能会得到这样的东西:

<GroupBox Width="{Binding Path=MyGroupBoxWidth, Mode=OneWayToSource}"/>

MSDN:

OneWayToSource: Updates the source property when the target property changes.

设置此设置会导致代码中的 属性 更新,但反之则不会