Benjamin Diele
Benjamin Diele

Reputation: 1187

Binding to a second property

I have two properties in my viewmodel, called Premises and Towns. I'm binding my ListViewItems to Premises, and in the itemtemplate I want to bind to Towns, but when I use the following XAML it tries to bind to Premises.Towns instead of Towns.

How can I bind to Towns directly?

Viewmodel:

public class MainWindowViewModel
{
    public ObservableCollection<Premise> Premises;
    public List<Town> Towns;
}

XAML:

    <ListView x:Name="PremisesList" Margin="195,35,10,10"
              ItemContainerStyle="{StaticResource OverviewListViewItemStyle}"
        ItemsSource="{Binding Premises}" HorizontalContentAlignment="Stretch">

And this is what's in my OverviewListViewItemStyle.

    <ComboBox ItemsSource="{Binding Towns}" Grid.Row="2" Grid.ColumnSpan="3">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <ComboBoxItem>
                    <TextBox Text="{Binding Name}" />
                </ComboBoxItem>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

I'd like to be able to select a Town for a Premise via XAML.

Upvotes: 1

Views: 57

Answers (2)

MDoobie
MDoobie

Reputation: 282

You bind the ItemsSource to the Premises property therefore if you bind to the Towns in the OverviewListViewItemStyle the binding engine will look up in the Premise object for a property called Towns. If you want to select a town for a premises you should tell to the combobox where to look from that property. You can try to set the combobox's datacontext to the main viewmodel with relative source in the binding. Something like that: ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.Towns}"

Upvotes: 1

dkozl
dkozl

Reputation: 33384

You are correct in your assumption. ComboBox looks for Towns in Premise class, which is the class behind each ListViewItem If you want to refer to same context as ListView you need to use RelativeSource binding.

<ComboBox
    ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.Towns}" 
    Grid.Row="2" 
    Grid.ColumnSpan="3" 
    DisplayMemberPath="Name"/>

Not related to your problem but you also don't need to specify DataTemplate to display single property. DisplayMemberPath will work as well. If you do specify DataTemplate you don't need to use ComboBoxItem as ComboBox will wrap DataTemplate content in ComboBoxItem so effectively you'll end up with ComboBoxItem inside another ComboBoxItem

Upvotes: 2

Related Questions