简体   繁体   English

WPF ListBox项目命令绑定

[英]WPF ListBox items command binding

I got following listbox 我有以下列表框

<Page.DataContext>
    <self:NewUserViewModel/>
</Page.DataContext>
<ListBox x:Name="PermissionLbox"  ItemsSource="{Binding ListFromDataContext}" Height="75" Margin="10,117,10,0" VerticalAlignment="Top">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding .}"></CheckBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Why if I change CheckBox definition to: 为什么将CheckBox定义更改为:

<CheckBox Command={Binding CommandFromDataContext} Content="{Binding .}"></CheckBox><CheckBox   Content="{Binding .}"></CheckBox>

name CommandFromDataContex cannot be resolved although CommandFromDataContext exists in NewUserViewModel. 名称CommandFromDataContex无法解析,尽管NewUserViewModel中存在CommandFromDataContext。 The ListFromDataContext is a property of NewUserViewModel, Command either, but Command is not resolved. ListFromDataContext是NewUserViewModel的属性,也可以是Command,但不能解析Command。

The datacontext of the checkbox isnt the viewmodel any more, but rather the individual item it instances in the listbox. 复选框的数据上下文不再是视图模型,而是列表框中它实例化的单个项。

You need to bind to a RelativeSource and Path to get to the ViewModel again. 您需要绑定到RelativeSource和Path才能再次进入ViewModel。

See existing answer for details. 有关详细信息,请参见现有答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM