silverlight-2.0 - 在 Silverlight 的列表框中访问父数据上下文

标签 silverlight-2.0

在 Silverlight 2 中,我使用了一个用户控件,它继承了它所嵌入的页面的数据上下文。此数据上下文包含问题文本、问题类型和答案集合。在用户控件中有一个列表框,它绑定(bind)到答案集合。如下所示:

<ListBox DataContext="{Binding}" x:Name="AnswerListBox" ItemContainerStyle="{StaticResource QuestionStyle}" Grid.Row="1" Width="Auto" Grid.Column="2" ItemsSource="{Binding Path=AnswerList}" BorderBrush="{x:Null}" />       

此列表框具有关联的样式,以单选按钮或复选框的形式显示答案(我想根据问题类型隐藏或显示):
<Style TargetType="ListBoxItem" x:Key="QuestionStyle">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">                      
                        <StackPanel Background="Transparent" >
                            <RadioButton Visibility="{Binding Path=QuestionType, Converter={StaticResource QuestionTypeConverter}, ConverterParameter='RadioButtonStyle'}" Height="auto" Margin="0,0,0,10"  IsChecked="{TemplateBinding IsSelected}" IsHitTestVisible="False" Content="{Binding Path=AnswerText}">
                            </RadioButton>
                            <CheckBox Visibility="{Binding Path=QuestionType, Converter={StaticResource QuestionTypeConverter}, ConverterParameter='CheckBoxStyle'}" Height="auto" Margin="0,0,0,10" Content="{Binding Path=AnswerText}">
                            </CheckBox>
                        </StackPanel>                                                
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

所以我的问题是:如何访问父数据上下文以获取 QuestionType(因为这是用户控件数据上下文本身的属性,而不是 AnswerList 中 AnswerItem 的属性)?

或者,是否有更好的方法根据绑定(bind)值在 xaml 中动态切换样式?

最佳答案

在 Silverlight 3 及更高版本中,您可以使用 Element 到 Element 绑定(bind)并指向控件 DataContext,然后在我的示例中指向其 Threshold 属性。

所以首先命名您的控件(例如在我的示例中它的 x:Name="control")

<UserControl x:Class="SomeApp.Views.MainPageView" x:Name="control" >

然后在您的 ListBox ItemTemplate 中的此控件内,您可以像这样访问父 DataContext:
    <ListBox ItemsSource="{Binding Path=SomeItems}" >
        <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding ElementName=control, Path=DataContext.Threshold}"/>
            </StackPanel>
        </DataTemplate>
       </ListBox.ItemTemplate>         
       </ListBox>

关于silverlight-2.0 - 在 Silverlight 的列表框中访问父数据上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/385784/

相关文章:

Silverlight 架构指南 - 延迟加载

xaml - 如何从Silverlight中的XAML中定义的用户控件正确继承

.net - 扩展方法是否太昂贵?

.net 运行时 - Silverlight 运行时 =?

asp.net - 如何在构建时将 Silverlight XAP 复制到 clientbin

Javascript/Silverlight 代理双加载延迟

silverlight - 在 Silverlight 中更改 Datagrid 标题的背景颜色

wpf - 您如何让 Silverlight 调整文本内容的大小以适合?

c# - Silverlight XAML 对象的二进制序列化