2012-04-03 33 views
1

我創建了一個從另一個Control繼承的UserControl。我現在搜索一個方法來更改BaseControl的DependencyProperty的默認值。在WPF中,我可以使用OverrideMetadata覆蓋DependecyProperty的DefaultValue。但OverrideMetadata在Silverlight中不可用。在Silverlight中更改DependencyProperty的DefaultValue

有人可以給我一個提示,我如何可以在Silverlight中更改DependencyProperty的DefaultValue?

回答

-1
 public static readonly DependencyProperty TextProperty = 
     DependencyProperty.Register("Text", typeof(string), typeof(MyClass), new PropertyMetadata(string.Empty)); 
     public string Text 
     { 
      get { return (string)GetValue(TextProperty); } 
      set { SetValue(TextProperty, value); } 
     } 

在這部分要設置的默認值:

new PropertyMetadata(string.Empty) 

它將與一個空字符串總是被啓動。

編輯:

嗯,我真的想解決這個問題。我認爲在一個解決方案,似乎並不是最正確的,我們可以嘗試一起改善。 爲此在你的基類:

public virtual void DefineDefaultValue(object default) 
    { 
     defaultValue = default; 
        OnPropertyChanged("MyProperty"); 
    } 

    static object defaultValue; 
    public static object Define() 
    { 
     return defaultValue; 
    } 

    public int MyProperty 
    { 
     get { return (int)GetValue(MyPropertyProperty); } 
     set { SetValue(MyPropertyProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.Register("MyProperty", typeof(int), typeof(MainMenuBase), new PropertyMetadata((int)Define())); 

畢竟,在你的類的構造函數做到這一點:

 public void ClassConstructor() 
    { 
     DefineDefaultValue("BlaBlaBla"); 
    } 

    public override void DefineDefaultValue(object default) 
    { 
     base.DefineDefaultValue(default); 
    } 
+0

謝謝您的回答。但在我的情況下,我的控件繼承自另一個控件,例如已經有一個TextProperty,並帶有DefaultValue string.Empty。我想現在在我的控制下,只將DefaultValue更改爲「blabla」。不創建新的財產! – BennoDual 2012-04-03 13:21:44

+0

哦,對不起。我找到了答案,但沒有找到答案。只需設置本地值不會幫助你,會嗎? – Vinicius 2012-04-03 13:56:05

+0

現在編輯...看一看。 – Vinicius 2012-04-03 14:23:48

相關問題