简体   繁体   中英

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 Command={Binding CommandFromDataContext} Content="{Binding .}"></CheckBox><CheckBox   Content="{Binding .}"></CheckBox>

name CommandFromDataContex cannot be resolved although CommandFromDataContext exists in NewUserViewModel. The ListFromDataContext is a property of NewUserViewModel, Command either, but Command is not resolved.

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.

See existing answer for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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