【问题标题】:Access ListBoxItem-Controls from code-behind从代码隐藏访问 ListBoxItem-Controls
【发布时间】:2011-03-29 13:24:36
【问题描述】:

在我的 Silverlight 4 应用程序中,我有一个列表框,我为它创建了一个 itemtemplate:

    <DataTemplate x:Key="ItemTemplate">
        <Grid Background="{StaticResource BrushCharacteristicListBoxItemBackground}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="10"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <TextBlock x:Name="TextBlockCharacteristicName" Text="{Binding Name}" TextTrimming="WordEllipsis" ToolTipService.ToolTip="{Binding Name}" Margin="6,0,2,0" VerticalAlignment="Center" HorizontalAlignment="Left" />
            <TextBlock x:Name="TextBlockSeperator" Text="=" Grid.Column="1" VerticalAlignment="Center" />
            <Border Grid.Column="2" HorizontalAlignment="Right" Margin="2,2,6,2" Background="{Binding FunctionState, Converter={StaticResource ConvertCharacteristicFunctionState2Color}}">
                <TextBlock x:Name="TextBlockCharacteristicValue" Text="{Binding CalculatedValue, Converter={StaticResource ConvertDouble2Display}}" Padding="2,0" Foreground="{StaticResource BrushCharacteristicListBoxItemBackground}" ToolTipService.ToolTip="{Binding ValueOrFunc}" MaxWidth="72"/>
            </Border>
        </Grid>
    </DataTemplate>     

现在我想从后面的代码中访问模板中定义的控件(即 TextBlockCharacteristicName)。我需要这个来手动调整控件的大小,这是其他方式无法完成的。

我挂接到了 LayoutUpdated 事件,但没有找到访问控件的方法。 我已经尝试过

((StackPanel)ListBoxCharacteristics.GetItemsHost()).Children

这给了我一个 ListBoxItems 的列表,但似乎没有办法从那里获取控件。无论如何都可以帮我解决这个问题吗?

提前致谢,
弗兰克

【问题讨论】:

  • 您确定不能将单个项目的高度绑定到(附加)属性吗?应该可以的。
  • 我需要调整单个项目的宽度,问题是,这个宽度取决于其他 ListItems:DesiredWidth = Min(Max(AllSimilarItems), MaxWidth)。我认为绑定不可能做到这一点。

标签: silverlight listbox


【解决方案1】:

从此博客中获取一小段 VisualTreeEnumeration 代码:Visual Tree Enumeration

现在您可以使用以下代码找到您的“TextBlockCharacteristicName”元素:-

foreach (var textBlock in ListBoxCharacteristics.Descendents()
    .OfType<TextBlock>()
    .Where(t => t.Name == "TextBlockCharacteristicName") )
{
    // Do stuff with each Text block.
}

【讨论】:

    猜你喜欢
    • 2011-02-28
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多