日期:2014-05-18  浏览次数:21135 次

WPF,一个控件绑定另一控件宽高的最好方法是什么?
不是简单的获取父级宽高后赋值。
例:
<DockPanel Name="MainDockPanel" Background="Blue">
  <ToolBar DockPanel.Dock="Top" Height="30"></ToolBar>
  <Grid DockPanel.Dock="Left" Name="LeftGrid">
  <WebBrowser></WebBrowser>
  </Grid>
  <Grid DockPanel.Dock="Right" Name="RightGrid"></Grid>
</DockPanel>

-------------
希望得到的效果,无论父级或窗口怎样改变大小RightGrid的宽永远都是MainDockPanel宽度的30%。

不知道在XAML中该如何赋于百分比值给元素属性。

请帮忙给出解决方法,谢谢。

------解决方案--------------------
去掉多余的DockPanel.Dock,放着也没用
XML code

<DockPanel Name="MainDockPanel" Background="Blue">
    <ToolBar DockPanel.Dock="Top" Height="30"></ToolBar>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="0" Name="LeftGrid">
            <WebBrowser></WebBrowser>
        </Grid>
        <Grid Grid.Column="1" Name="RightGrid"></Grid>
    </Grid>
</DockPanel>

------解决方案--------------------
纠正一下,你这是1/4,不是30%

<ColumnDefinition Width="3*" />
<ColumnDefinition Width="*" />

------解决方案--------------------
C# code

var grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(3, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(7, GridUnitType.Star) });

var button1 = new Button { Content = "Left - 3*" };
button1.SetValue(Grid.ColumnProperty, 0);
grid.Children.Add(button1);

var button2 = new Button { Content = "Right - 7*" };
button2.SetValue(Grid.ColumnProperty, 1);
grid.Children.Add(button2);

this.Content = grid;

// now change
grid.ColumnDefinitions[0].Width = new GridLength(2, GridUnitType.Star);
grid.ColumnDefinitions[1].Width = new GridLength(8, GridUnitType.Star);