在Silverlight中访问列表框中的父datacontext

Jam*_*195 24 silverlight-2.0

在Silverlight 2中,我使用的是usercontrol,它继承了它所嵌入的页面的datacontext.此datacontext包含问题文本,问题类型和答案集合.在用户控件中是一个列表框,它绑定到答案集合.如下所示:

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

此列表框具有相关的样式,以单选按钮或复选框的形式显示答案(我想根据问题类型隐藏或显示):

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*lob 55

在Silverlight 3及更高版本中,您可以使用Element to Element绑定并指向控件DataContext,然后在我的示例中指向其Threshold属性中的某些属性.

首先命名你的控件(例如在我的例子中它的x:Name ="control")

<UserControl x:Class="SomeApp.Views.MainPageView" x:Name="control" >
Run Code Online (Sandbox Code Playgroud)

然后在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>
Run Code Online (Sandbox Code Playgroud)

  • 重要的是不要错过你需要明确放入'DataContext'.我之前放弃了尝试这样做的原因,因为我设法忘了放'DataContext' (4认同)