微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

<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,10"  IsChecked="{TemplateBinding IsSelected}" IsHitTestVisible="False" Content="{Binding Path=AnswerText}">
                            </RadioButton>
                            <CheckBox Visibility="{Binding Path=QuestionType,ConverterParameter='CheckBoxStyle'}" Height="auto" Margin="0,10" Content="{Binding Path=AnswerText}">
                            </CheckBox>
                        </StackPanel>                                                
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

所以我的问题是:你如何访问父数据上下文为了得到QuestionType(因为这是一个属性用户控制数据报文本身,而不是一个属性在AnswerList的AnswerItem)?

或者有一个更好的方法在xaml中基于绑定值动态切换样式?

解决方法

在Silverlight 3和更高版本中,您可以使用元素到元素绑定并指向控件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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐