【问题标题】:2 identical DependencyProperties on different pages不同页面上的 2 个相同的依赖属性
【发布时间】:2015-03-02 07:54:10
【问题描述】:

我有一个名为 H1Property 的 DependencyProperty,声明如下:

Public Shared ReadOnly H1Property As DependencyProperty = DependencyProperty.Register("H1", GetType(String), GetType(Button), Nothing)
Public Property H1() As String
    Get
        Return DirectCast(GetValue(H1Property), String)
    End Get
    Set(ByVal value As String)
        SetValue(H1Property, value)
    End Set
End Property    

在page1中,我使用它为带有自定义模板的按钮分配一个值(例如template1,需要在不同的页面上使用相同的模板,所以它存储在App.xaml中)。我在项目中还有另一个页面(page2),在代码隐藏中具有相同的 H1Property。当我在 page1 上使用 template1 动态添加按钮时,它工作正常,但是当我导航到 page2,然后返回 page1 并再次生成控件时,新按钮中的值是空的。没有错误,只有空字段。

有什么问题?有没有办法只声明一次 DependencyProperty,然后在不同的页面上使用它?

提前致谢。

【问题讨论】:

    标签: vb.net windows-runtime windows-phone-8.1 dependency-properties


    【解决方案1】:

    你可以有一个模块来存储公共状态并在页面中引用它

    Public Module CommonState
        Public ReadOnly H1Property As DependencyProperty = _
            DependencyProperty.Register("H1", GetType(String), GetType(Button), Nothing)
    End Module
    

    在两个页面上

    Public Property H1() As String
        Get
            Return DirectCast(GetValue(CommonState.H1Property), String)
        End Get
        Set(ByVal value As String)
            SetValue(CommonState.H1Property, value)
        End Set
    End Property    
    

    如果您需要页面本身的H1Property,您可以将其包装到一个属性中

    Public Shared ReadOnly Property H1Property() As DependencyProperty
       Get
          Return CommonState.H1Property
       End Get
    End Property
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2020-09-15
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多