【发布时间】:2011-04-07 20:18:13
【问题描述】:
我有一个页面,其中有一个包含 2 列的网格,一个可容纳 80* 宽度,另一个可容纳 20*。网格下方是一个堆栈面板,我在运行时将 UI 元素(子堆栈面板)加载到该面板。
我的目标是将堆栈面板的宽度绑定到网格的列。如果动态内容在设计视图中被模拟为静态,这可以完美地工作,并且 stackpenels 会调整大小。但是当应用程序运行时,绑定失败,宽度没有绑定。
有没有办法刷新绑定,以便我可以通知堆栈面板参考网格的宽度并配置其大小?
更新: 这就是我的 XAML 的样子:
<Page x:Class="WPFTestApp.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid x:Name="resizeGrid"
Grid.Column="0" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="leftColumn"
Width="80*" />
<ColumnDefinition x:Name="rightColumn"
Width="20*" />
</Grid.ColumnDefinitions>
</Grid>
<StackPanel x:Name="contentPanel"
Grid.Column="0" Grid.Row="0" >
<!-- Dynamic StackPanels are added here -->
</StackPanel>
</Grid>
</Page>
在我的代码中,我创建了 StackPanel 元素并将其添加到 contentPanel,方法是: contentPanel.Children.Add(...);
不幸的是,我必须在这里使用 StackPanels。 :-(
动态创建的 StackPanel 元素的标记如下(注意我在 XAML 中使用了对网格的 Binding):
<StackPanel x:Name="element01"
Orientation="Horizontal"
Width="{Binding ElementName=resizeGrid, Path=ActualWidth}" >
<StackPanel x:Name="leftPanel"
Orientation="Vertical"
Width="{Binding ElementName=leftColumn, Path=ActualWidth}">
<!-- Content goes here -->
</StackPanel>
<StackPanel x:Name="rightPanel"
Orientation="Vertical"
Width="{Binding ElementName=rightColumn, Path=ActualWidth}">
<!-- Content goes here -->
</StackPanel>
</StackPanel>
我的动态 StackPanel 元素的 XAML 代码是通过 XSLT 转换生成的
注意 xmlns:x 命名空间动态 StackPanel。这也必须完成,因为它是通过 XSLT 生成的
【问题讨论】:
-
如果将 StackPanel 添加到 Grid 中,它将自动扩展以填充已添加到的列的整个宽度。
-
我已经更新了帖子的更多细节。谢谢!
标签: wpf dynamic binding element