【问题标题】:Binding a TextBox's Width to its parent container's ActualWidth将 TextBox 的 Width 绑定到其父容器的 ActualWidth
【发布时间】:2010-12-31 18:34:14
【问题描述】:

我正在以编程方式将TextboxButton 加载到水平StackPanel 中。按钮的大小(仅包含Image)是固定的,但我无法让文本框填充其父级的可用宽度。代码是这样的:

StackPanel parent = new StackPanel() {
  Orientation = Orientation.Horizontal,
  HorizontalAlignment = HorizontalAlignment.Stretch,
  VerticalAlignment = VerticalAlignment.Top,
};

TextBox textbox = new TextBox() {
  HorizontalAlignment = HorizontalAlignment.Stretch,
  VerticalAlignment = VerticalAlignment.Top,
  //MinWidth = 375,
};

Button btn = new Button() {
  Content = new Image() {
    MaxHeight = 40,
    MaxWidth = 40,
    MinHeight = 40,
    MinWidth = 40,
    Margin = new Thickness( 0 ),
    Source = new BitmapImage( 
      new Uri( "btnimage.png", UriKind.Relative ) ),
  },
  HorizontalAlignment = HorizontalAlignment.Right,
  BorderBrush = new SolidColorBrush( Colors.Transparent ),
  Margin = new Thickness( 0 ),
};
btn.Click += ( ( s, e ) => OnBtnClicked( s, e, textbox ) );

parent.Children.Add( textbox );
parent.Children.Add( btn );

如果我取消注释文本框的 MinWidth 设置,它将按我想要的方式显示,但我不想明确指定宽度。我尝试按如下方式添加绑定,但这根本不起作用(文本框消失了!)

Binding widthBinding = new Binding() {
  Source = parent.ActualWidth,
};
passwdBox.SetBinding( TextBox.WidthProperty, widthBinding );

提前感谢您的帮助!

【问题讨论】:

    标签: windows-phone-7 binding textbox width actualwidth


    【解决方案1】:

    不要使用StackPanel(它总是尽量保持元素尽可能小,以便它们都适合),而是使用Grid。然后你可以这样做:

    <Grid>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/> <!-- Note "*" means to use the rest of the space -->
        <ColumnDefinition Width="40"/>
      </Grid.ColumnDefinitions>
      <TextBox Grid.Column="0"/>
      <Button Grid.Column="1">
        <Button.Content>
          <Image .../>
        </Button.Content>
      </Button>
    </Grid>
    

    如果您愿意,可以将其转换为代码而不是 XAML,XAML 只是更容易在此处即时键入。

    【讨论】:

      【解决方案2】:

      正确的答案是不要这样做。请参阅我的回答 at this question,同样的想法也适用于 Windows Phone 上的 Silverlight。

      在您的示例中,您应该使用DockPanel

      <toolkit:DockPanel>
          <Button toolkit:DockPanel.Dock="Right" />
          <TextBox /> <!-- fill is implied -->
      </toolkit:DockPanel>
      

      【讨论】:

      • 这看起来像我需要的,但我在 Windows Phone 的 Silverlight 工具包中找不到 DockPanel。我只是尝试重新安装它以确保我拥有最新版本,但仍然没有运气。
      • 在决定使用工具包组件时应该小心。这些将增加 Xap 的整体尺寸,这可能是 WP7 的一个重要考虑因素。如果添加工具包 dll 的唯一原因是让这一功能正常工作,则应寻求替代的非工具包解决方案。
      • 非常好,安东尼。如果您还没有使用 Silverlight 工具包,那么我将使用 Grid。但是拥有 DockPanel 对于各种布局非常有用。您几乎总是可以将 Grid 用于此类布局,但正如您在 Austin 的回答中看到的那样,基于 Grid 的布局可能会变得非常冗长。
      猜你喜欢
      • 2012-10-04
      • 1970-01-01
      • 2011-04-08
      • 2011-05-20
      • 2011-01-28
      • 1970-01-01
      • 2013-06-29
      • 2010-12-08
      • 2016-10-04
      相关资源
      最近更新 更多