【问题标题】:One way binding to Static property doesn't update the target when source changes当源更改时,绑定到静态属性的一种方法不会更新目标
【发布时间】:2017-02-08 08:21:54
【问题描述】:

我有一个静态属性,在一个静态类中,我已绑定到框架的 Source 属性。它是一种单向绑定。绑定第一次正常工作,但在属性更改时不会更新目标。这是我的 XAML

<Frame x:Name="frmMain" Source="{Binding Source={x:Static currentPage:ActivePages.MainFramePage}, NotifyOnTargetUpdated=True,Mode=OneWay}"/>

这是我的静态类 ActivePages.cs

public static class ActivePages
    {
        private static Uri mainFramePage;
        public static Uri MainFramePage
        {
            get { return mainFramePage; }
            set
            {
                mainFramePage = value;
                MainFramePageChanged?.Invoke(null, new PropertyChangedEventArgs("MainFramePage"));
            }
        }
public static event EventHandler<PropertyChangedEventArgs> MainFramePageChanged;
}

我关注了this linkanother link
当源更改时,我如何更新它?

【问题讨论】:

    标签: wpf binding static


    【解决方案1】:

    如果是 WPF 4.5 或更高版本,您可以使用 Path 属性:

     <Frame x:Name="frmMain" Source="{Binding Path=(local:ActivePages.MainFramePage), NotifyOnTargetUpdated=True,Mode=OneWay}"/>
    

    【讨论】:

      【解决方案2】:

      根据MSDN page,静态属性更改事件的签名是

      public static event EventHandler MyPropertyChanged;
      

      public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
      

      所以你的应该是

      public static event EventHandler MainFramePageChanged;
      

      而不是

      public static event EventHandler<PropertyChangedEventArgs> MainFramePageChanged;
      

      但是,如果你有多个静态属性,你最好使用单个事件

      public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
      

      PropertyChangedEventArgs 提供属性名称信息。


      您还应该对 Binding 表达式使用以下语法:

      Source="{Binding Path=(currentPage:ActivePages.MainFramePage)}"
      

      有关静态属性更改通知的详细信息,另请参阅this blog post

      【讨论】:

      • 我无法访问该博客的链接。并且您指定源的语法不会加载框架源
      • 好的,链接好像坏了,可能只是暂时的。绑定表达式语法可能不适用于较旧的 WPF 版本。你用的是什么版本?你也可以看看这个答案:stackoverflow.com/a/41823852/1136211
      • 当然绑定路径应该是currentPage:ActivePages.MainFramePage,而不是local:ActivePages.MainFramePage
      • 你能告诉我博客的内容吗,因为链接还是坏了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多