bas
bas

Reputation: 14902

WPF DataContext not updating children

I am trying to use data binding on my first custom user control in WPF. Unfortunately the UI never receives updates.

Declaration of custom user control:

<views:EpisodeDetailsUserControl 
    x:Name="EpisodeDetailsUserControl" 
    DataContext="{Binding Episode}"/>

Custom user control xaml (snippet):

    <Label 
        x:Name="TvShowNameLabel" 
        Grid.Row="0" 
        Grid.Column="1" 
        DataContext="{Binding TvShowName}" />

    <Label 
        x:Name="SeasonIdLabel" 
        Grid.Row="1" 
        Grid.Column="1" 
        DataContext="{Binding SeasonId}" />

I expected the user control to be updated when:

    private void DowloadedEpisodesListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var episode = DowloadedEpisodesListView.SelectedItem as IEpisode;

        if (episode != null)
        {
            EpisodeDetailsUserControl.DataContext = episode; // <======
        }
    }

For completeness, IEpisode

public interface IEpisode
{
    string FileName { get; }
    string FullPath { get; }
    string Directory { get; }
    string Extension { get; }

    string TvShowName { get; set; }
    int SeasonId { get; set; }
    int Id { get; set; }
    string Name { get; }

    bool IsValid { get; }
    string NewFileName { get; }
    string RenameProposal { get; }
}

But no luck, nothing happens.

Can somebody point me in the right direction?

Upvotes: 2

Views: 1187

Answers (1)

max
max

Reputation: 34407

You should bind label Content property instead of DataContext:

<Label x:Name="SeasonIdLabel" 
       Grid.Row="1" Grid.Column="1" 
       Content="{Binding SeasonId}" />

Also, you probably could bind EpisodeDetailsUserControl.DataContext to DowloadedEpisodesListView directly to get rid of that event handler in code-behind:

DataContext="{Binding ElementName=DowloadedEpisodesListView, Path=SelectedItem}"

Upvotes: 2

Related Questions