2010-04-23 58 views
1

我已經將依賴屬性MyList添加到wpf文本框中。依賴屬性的類型爲列表<字符串>。爲了使事情更容易XAML我已經定義了一個轉換器,這樣我可以有以下的語法:WPF Visual Studio Designer和Expression Blend不依賴DependencyProperty上的TypeConverter

<Grid> 
    <controls:MyTextBox x:Name="Hello" MyList="One,Two" Text="Hello" /> 
</Grid> 

在Visual Studio中,我不能在所有編輯財產和Expression Blend中我可以輸入字符串但它會產生下面的XAML代碼:

<controls:MyTextBox x:Name="Hello" Text="Hello" > 
<controls:MyTextBox.MyList> 
    <System_Collections_Generic:List`1 Capacity="2"> 
    <System:String>One</System:String> 
    <System:String>Two</System:String> 
    </System_Collections_Generic:List`1> 
</controls:MyTextBox.MyList> 
</controls:MyTextBox> 

任何想法如何我可以在這兩個Visual Studio中編輯此屬性爲一個字符串,混合?

public class MyTextBox : TextBox 
{ 
    [TypeConverter(typeof(MyConverter))] 
    public List<string> MyList 
    { 
     get { return (List<string>)GetValue(MyListProperty); } 
     set { SetValue(MyListProperty, value); } 
    } 

    public static readonly DependencyProperty MyListProperty = DependencyProperty.Register("MyList", typeof(List<string>), typeof(MyTextBox), new FrameworkPropertyMetadata(new List<string> { "one" })); 
} 


public class MyConverter : TypeConverter 
{ 
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 
    { 
     if(sourceType == typeof(string)) 
      return true; 
     return base.CanConvertFrom(context, sourceType); 
    } 

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) 
    { 
     if(value is string) 
      return new List<string>(((string)value).Split(','));  

     return base.ConvertFrom(context, culture, value); 
    } 

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 
    { 
     if(destinationType == typeof(string)) 
      return true; 
     return base.CanConvertTo(context, destinationType); 
    } 

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 
    { 
     if(destinationType == typeof(string)) 
     { 
      var ret = string.Empty; 
      var s = ret; 
      ((List<string>)value).ForEach(v => s += s + v + ","); 
      ret = ret.Substring(0, ret.Length - 1); 

      return ret; 
     } 

     return base.ConvertTo(context, culture, value, destinationType); 
    } 
} 

回答

0

有與泛型這樣做沒有可能,既VS和Blend設計會產生與標籤收集信息,一邊做設計時序列化。解決辦法之一是爲MyList而不是List創建自己的數據類型。 :(

或者

你需要保持MYLIST作爲一個String屬性然後,分析後續的字符串,並將其存儲到一個列表。

或者

還有一個可能的解決方案。[如果你知道前面列表的值]

而不是使用一個List<string>使它成爲Flags的枚舉,所以,你可以在VS Designer和Blend中得到預期的輸出語法,而不需要那些垃圾代碼。

HTH