WPF binding to Listbox selectedItem

Oli Baylis picture Oli Baylis · Jan 6, 2010 · Viewed 115.4k times · Source

Can anyone help with the following - been playing about with this but can't for the life of me get it to work.

I've got a view model which contains the following properties;

public ObservableCollection<Rule> Rules { get; set; }
public Rule SelectedRule { get; set; }

In my XAML I've got;

<ListBox x:Name="lbRules" ItemsSource="{Binding Path=Rules}" 
         SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
    <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Name:" />
                <TextBox x:Name="ruleName">
                    <TextBox.Text>
                        <Binding Path="Name" UpdateSourceTrigger="PropertyChanged" />
                    </TextBox.Text>
                </TextBox>
            </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

Now the ItemsSource works fine and I get a list of Rule objects with their names displayed in lbRules.

Trouble I am having is binding the SelectedRule property to lbRules' SelectedItem. I tried binding a textblock's text property to SelectedRule but it is always null.

<TextBlock Text="{Binding Path=SelectedRule.Name}" />

The error I'm seeing in the output window is: BindingExpression path error: 'SelectedRule' property not found.

Can anyone help me with this binding - I can't see why it shouldn't find the SelectedRule property.

I then tried changing the textblock's text property as bellow, which works. Trouble is I want to use the SelectedRule in my ViewModel.

<TextBlock Text="{Binding ElementName=lbRules, Path=SelectedItem.Name}" />

Thanks very much for your help.

Answer

arconaut picture arconaut · Jan 6, 2010

First off, you need to implement INotifyPropertyChanged interface in your view model and raise the PropertyChanged event in the setter of the Rule property. Otherwise no control that binds to the SelectedRule property will "know" when it has been changed.

Then, your XAML

<TextBlock Text="{Binding Path=SelectedRule.Name}" />

is perfectly valid if this TextBlock is outside the ListBox's ItemTemplate and has the same DataContext as the ListBox.