Search code examples
c#wpfdata-bindingtelerikrelativesource

WPF how to access other variable from same viewmodel?


To display items on Telerik:RadGridView usually I use DataContext="{Binding [someViewModel]}" and ItemSource="{Binding objectList, Mode=TwoWay}".

and for my column I'll access the objectfield. The overall picture will be something like below:

<telerik:RadGridView DataContext="{Binding [someViewModel]}" 
     ItemSource="{Binding objectList, Mode=TwoWay}">

    <telerik:RadGridView.Columns>
            <telerik:GridViewDataColumn>
                <telerik:GridViewDataColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsEnabled="{Binding enabledVar}" 
                            IsChecked="{Binding isChecked, Mode=Twoway}"
                    </DataTemplate>
                </telerik:GridViewDataColumn.CellTemplate>

            </telerik:GridViewDataColumn>  
    </telerik:RadGridView.Columns>

</telerik:RadGridView>

Imagine there will be 10 items in objectList. Each of the item in objectList will have a variable isChecked which to manipulate the checkbox IsChecked property.

I have another variable in the same viewmodel named enabledVar which to control the ten checkbox IsEnabled property. enabledVar is not part of the objectList but I couldn't get the value. May I know how to handle such case?

Updates:

I've found some new direction but not sure if it helps.

<CheckBox IsEnabled="{Binding enabledVar,
     RelativeSource={RelativeSource Mode=FindAncestor, 
     AncestorType=telerik:RadGridView}}"

but then of course, still failed.

Any helps would be very much appreciated.


Solution

  • if using Ancestor you have to bind to DataContext

    <CheckBox IsEnabled="{Binding Path=DataContext.enabledVar,
         RelativeSource={RelativeSource Mode=FindAncestor, 
         AncestorType=telerik:RadGridView}}"
    

    Another aproach could be to use element binding set name

    <telerik:RadGridView x:Name="myGrid" ...
    

    And then in the celltemplate bind to it

    <CheckBox IsEnabled="{Binding Path=DataContext.enabledVar, ElementName=myGrid}"
    

    Hope this helps.