slashms
slashms

Reputation: 978

How to Bind all ListBox's Items to the same Property?

I have a ListBox with the following DataTemplate:

        <DataTemplate x:Key="ItemTmp">
        <Border Name="Border" BorderBrush="Aqua" BorderThickness="1" Padding="5" Margin="5">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>

                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Path=Item1}"></TextBlock>
                <TextBlock Grid.Column="1" Text="{Binding Path=Item2}"></TextBlock>
                <TextBox  Grid.Column="2" Text="{Binding Path=UpdatedGrade,UpdateSourceTrigger=LostFocus,Mode=TwoWay }" />
            </Grid>
        </Border>
    </DataTemplate>
</UserControl.Resources>

Means, I want that everytime user writes something in one of the text boxes , it will update the same field in the ViewModel - UpdatedGrade , problem is that it doesn't work.

When I just bind a single TextBox to this field, it does works, for example:

TextBox Grid.Row="3" Text="{Binding Path=UpdatedGrade,UpdateSourceTrigger=LostFocus,Mode=TwoWay }"></TextBox>

Does anyone have any idea how can I do it?

Upvotes: 1

Views: 44

Answers (1)

bdimag
bdimag

Reputation: 963

The DataContext of a ListBox item is of the individual item in the collection, so it's trying to find to a Property of that item.

As long as this is not a windows store app, you can do something like this:

Text="{Binding Path=DataContext.UpdatedGrade, UpdateSourceTrigger=LostFocus, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"

with win8 apps you can't find ancestor as easily, so you'd have to give the name of the element that contains the context

Text="{Binding Path=DataContext.UpdatedGrade, UpdateSourceTrigger=LostFocus, Mode=TwoWay, ElementName=MyUserControl}"

I'm unsure of how this would act--binding directly to the textbox--it might update UpdatedGrade in the DataContext, but again, I'm not sure.

Text="{Binding Path=Text, UpdateSourceTrigger=LostFocus, Mode=TwoWay, ElementName=MyTextBox}"

Upvotes: 1

Related Questions