MoonKnight
MoonKnight

Reputation: 23831

Direct Binding on DataGrid Column

I have the following DataGrid

<DataGrid x:Name="CommentaryGrid"
          ...
          SelectedItem="{Binding SelectedCommentary, Mode=TwoWay}"
          ItemsSource="{Binding CommentaryCollection}"
          Helpers:DataGridTextSearch.SearchValue="{Binding ElementName=SearchTextBox, Path=Text, UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns>
    <DataGridTextColumn Header="Event ID" IsReadOnly="True" Binding="{Binding event_id}"/>
    <DataGridTextColumn Header="Team" IsReadOnly="True" Binding="{Binding team, Converter={StaticResource NullTeamToBlankStringConverter}}"/>
    <DataGridTextColumn Header="Bookie" IsReadOnly="True" Binding="{Binding bookie}"/>
    <DataGridTextColumn Header="Type" IsReadOnly="True" Binding="{Binding type}"/>
    <DataGridTextColumn Header="Value" IsReadOnly="True" Binding="{Binding value}"/>
    ...

CommentaryCollection is defined via

public ObservableCollection<Taurus.Commentary> CommentaryCollection { ... }

I need to not merely display the Taurus.Commentary.team property for an object, but first test another property for a condition (using my NullTeamToBlankStringConverter). So I want to pass the entire Taurus.Commentary object to my column binding. I can change the column definition to

<DataGridTextColumn Header="Team" IsReadOnly="True" Binding="{Binding Path=Items, ElementName=CommentaryGrid, Converter={StaticResource NullTeamToBlankStringConverter}}"/>

To bind to the ItemCollection, but this does not enable me to test for the object in each row (using my converter). In the converter using the ItemCollection approach, I can cast to ItemCollection and check CurrentItem but this will only give me the selected item and hence the same value for all rows. How can I bind to the entire Taurus.Commentary Item of the ItemSource?

Thanks for your time.

Upvotes: 1

Views: 276

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81323

Use IMultiValueConverter and pass the current object binding as second parameter.

<DataGridTextColumn>
    <DataGridTextColumn.Binding>
        <MultiBinding Converter="{StaticResource NullTeamToBlankStringConverter}">
            <Binding Path="Items" ElementName="CommentaryGrid"/>
            <Binding Path="."/>
        </MultiBinding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

NullTeamToBlankStringConverter needs to implement IMultiValueConverter instead of IValueConverter.

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61379

Use Binding Path=. to bind to the entire data context (for an item template, thats an item in the collection).

In your case, it would look like:

Binding="{Binding Path=., Converter={StaticResource NullTeamToBlankStringConverter}}"/>

Upvotes: 1

Related Questions