首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >吟唱ItemsSource DataContext

吟唱ItemsSource DataContext
EN

Stack Overflow用户
提问于 2015-09-23 21:17:32
回答 2查看 34关注 0票数 0

在我的ListBox ItemTemplate中,绑定到我的命令有问题。我的命令是在我的ViewModel中定义的,但是因为我使用ItemsSource作为我的列表框,所以它被设置为DataContext。

代码语言:javascript
复制
                 <ListBox ItemsSource="{Binding CreatureModel.TypeFlagsValues}">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <CheckBox Content="{Binding}" Command="{Binding SetCommand">
                                </CheckBox>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

我试过用RelativeSource

代码语言:javascript
复制
Command="{Binding SetCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:CreatureEditorViewModel}}}"

代码语言:javascript
复制
    <DataTemplate DataType="vm:CreatureEditorViewModel">
         <CheckBox Content="{Binding}" Command="{Binding SetCommand}" CommandParameter="test">
         </CheckBox>
    </DataTemplate>

我觉得我错过了一些简单的东西。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-23 21:45:45

你几乎把RelativeSource做得很好。

试试这个:

代码语言:javascript
复制
Command="{Binding Path=DataContext.SetCommand, 
                    RelativeSource={RelativeSource Mode=FindAncestor,      
                    AncestorType={x:Type ItemsControl}} }"

或者,您可以为列表框指定名称(例如"_listBox“),并使用以下绑定:

代码语言:javascript
复制
Command="{Binding DataContext.SetCommand, ElementName=_listBox}
票数 1
EN

Stack Overflow用户

发布于 2015-09-23 21:43:14

尝试在命令上设置ElementName和路径;您必须在ListBox上设置x:Name,然后可以引用父DataContext。

代码语言:javascript
复制
<ListBox x:Name="list" ItemsSource="{Binding CreatureModel.TypeFlagsValues}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" Command="{Binding ElementName=list,
               Path=DataContext.SetCommand}">                    
            </CheckBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32749650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档