2012-10-15 47 views
1

我正在處理一個C#WPF組件(包含VS2010版本10.0.40219.1 SP1Rel),其中包含像int和List這樣的公共屬性。XAML列表值設置器與預先存在的項目

成分似乎是由VS2010 WPF編輯細被序列化爲在的.xaml生成的XML塊是這樣的:

<Parent> 
    <NumberProperty>10</NumberProperty> 
    <ListProperty> 
     <Item> 
      blah 
     </Item> 
    </ListProperty> 
</Parent> 

當反序列化組分(即運行該應用程序)時,列表屬性是讀取(運行getter)並添加項目。列表中沒有運行setter的人。

問題是該列表故意包含默認項目,該項目被添加到項目父構造函數的列表中。這些/這個預先存在的項目應該被列表中的項目取代,如果有的話在相關的xaml中可用的話。

我試過DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)作爲list屬性沒有運氣。

所以有可能通過某些屬性告訴環境它應該替換列表屬性(調用setter)而不是向它添加項目?

回答

0

這是一個摸不到頭腦:)

正如你所說的,如果你初始化一些默認值的列表屬性,它們不會出現在設計師。如果向列表中添加一些值,則會將其序列化爲.xaml,然後在運行時將這些值添加到默認值中,而不是替換它們。

其中一個解決方案是使用知道它包含默認值(或值)的自定義集合,並在第一個新項目添加到列表中時將其刪除(或它們)。

例如

public partial class UserControl1 
{ 
    public UserControl1() 
    { 
     // initialise collection with '1' - doesn't appear in design time properties 
     Ids = new MyCollection<int>(1); 

     InitializeComponent(); 
    } 

    public int Id { get; set; } 

    public MyCollection<int> Ids { get; set; } 
} 

public class MyCollection<T> : Collection<T> 
{ 
    private readonly T _defaultValue; 
    private bool _hasDefaultValue; 

    public MyCollection(T defaultValue) 
    { 
     _defaultValue = defaultValue; 

     try 
     { 
      _hasDefaultValue = false; 

      Add(defaultValue); 
     } 
     finally 
     { 
      _hasDefaultValue = true; 
     } 
    } 

    protected override void InsertItem(int index, T item) 
    { 
     base.InsertItem(index, item); 

     if (_hasDefaultValue) 
     { 
      Remove(_defaultValue); 
      _hasDefaultValue = false; 
     } 
    } 
} 

的XAML

<local:UserControl1 Id="5"> 
     <local:UserControl1.Ids> 
      <System:Int32>2</System:Int32> 
      <System:Int32>3</System:Int32> 
      <System:Int32>4</System:Int32> 
     </local:UserControl1.Ids> 
    </local:UserControl1> 

我不能說這是一個特別令人愉悅的解決方案,但我認爲這不會解決你的問題。

+0

謝謝:)我有點害怕它必須由代碼完成。對於最終用戶的觀點(在我的情況下),可能會很好添加一個內部構造函數,它將'_hasDefaultValue'設置爲true,其他構造函數不是。但是這仍然會帶來麻煩,因爲無法分辨無參數構造函數是由用戶還是由xaml-loader調用的。而且我寧願不更改容器,因爲已經使用了以前的版本。我在列表getter中嘗試了類似的方法,這會清空列表,如果組件尚未初始化(醜陋)。需要更多的挖掘。 – user1746986

相關問題