开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜