简体   繁体   中英

How to bind to 2 different members in a class in WPF?

I have a class like:

class EditorViewModel
{
    public ObservableCollection<Effect> AllEffects;
    public bool HasPermissions;
}

But the problem is, when I am trying to bind AllEffects to ListView , then I can't bind anything to HasPermissions because the binding scope is limited to AllEffects , not EditorViewModel .

I tried this but it doesn't work:

<ListView ItemsSource="{Binding EditorViewModel}">

...

<GridViewColumn Width="Auto" Header="Name">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding AllEffects.Name}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

<GridViewColumn Width="Auto" Header="Type">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding AllEffects.Type}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

If I set the ItemsSource to EditorViewModel and get rid of AllEffects , it works. But then I don't know how to access HasPermissions through binding:

<GridViewColumn Width="50" Header="Override">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Margin="0"
                                    HorizontalAlignment="Center"
                                    IsEnabled="{Binding HasPermission}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

As I updated my answer on this question to include, you can bind the ListView to the AllEffects property of your ViewModel and then refer to a different property of the ViewModel using a relative binding. So assuming your ListView is contained in a Window whose DataContext is an EditorViewModel , and the ListView's ItemsSource is AllEvents , you can still reference HasPermission like so:

<CheckBox Margin="0"
          HorizontalAlignment="Center"
          IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.HasPermission}"/>

That somewhat clunky notation will find the nearest parent element to the CheckBox in the visual tree that is of type Window, and bind to its DataContext property to find HasPermission.

A classic trick is to use ViewModelLocator, see: MVVM Light - using ViewModelLocator - properties hit multiple times

also, for a more quick-and-dirty solution, you can use the following Binding:

{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}, Path=DataContext.HasPermissions}

Note that this would only work on WPF and not in SL, since SL doesn't support this syntax of RelativeSource.

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