WPF将MaxDropDownHeight属性绑定到网格行高度

时间:2013-03-24 09:37:22

标签: wpf combobox grid

我有一个comboBox,我想动态绑定MaxDropDownHeight属性到第二行高度。

这里是xaml:

  <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="6*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <ComboBox MaxDropDownHeight="">

    </ComboBox>
</Grid>

我该怎么做?

1 个答案:

答案 0 :(得分:1)

绑定到Grid的第二行,您可以通过两种方式实现:

首先:RelativeSource bining:

<ComboBox DropDownOpened="ComboBox_DropDownOpened" 
          MaxDropDownHeight="{Binding Path=RowDefinitions[1].ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, UpdateSourceTrigger=PropertyChanged}">       
</ComboBox>

第二:通过ElementName绑定(在这种情况下,您必须在网格Name="RootLayout"中设置):

<ComboBox DropDownOpened="ComboBox_DropDownOpened" 
          MaxDropDownHeight="{Binding ElementName=RootLayout, Path=RowDefinitions[1].ActualHeight, UpdateSourceTrigger=PropertyChanged}">            
</ComboBox>

DropDownOpened事件处理程序中,您应该使用MaxDropDownHeight类更新BindingExpression的值。

private void ComboBox_DropDownOpened(object sender, EventArgs e)
{
    ComboBox cb = sender as ComboBox;
    BindingExpression be = cb.GetBindingExpression(ComboBox.MaxDropDownHeightProperty);
    be.UpdateTarget();
}