【问题标题】:WPF DataContext not updating childrenWPF DataContext 不更新子级
【发布时间】:2013-11-16 18:54:43
【问题描述】:

我正在尝试在 WPF 中的第一个自定义用户控件上使用数据绑定。不幸的是,用户界面永远不会收到更新。

自定义用户控件的声明:

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

自定义用户控件 xaml (sn-p):

    <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}" />

我希望在以下情况下更新用户控件:

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

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

为了完整起见,请使用 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; }
}

但运气不好,什么也没有发生。

有人能指出正确的方向吗?

【问题讨论】:

  • 实现IEEpisode的类是否也实现了INotifyPropertyChanged?

标签: c# wpf data-binding custom-controls


【解决方案1】:

您应该绑定标签Content 属性而不是DataContext

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

另外,您可能可以直接将EpisodeDetailsUserControl.DataContext 绑定到DowloadedEpisodesListView 以摆脱代码隐藏中的事件处理程序:

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

【讨论】:

  • 啊啊啊!!所以这就是他们的意思!感谢答案和提示!两者都工作正常,我在其他地方做了同样丑陋的把戏,所以我可以摆脱更多冗余的代码隐藏。 NR1!谢谢!
猜你喜欢
  • 2014-01-02
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
相关资源
最近更新 更多