2013-11-27 17 views
1

我有很多SQLMetal爲我的WP Linq to SQL數據庫創建了一個數據類型爲nvarchar(##)的字段。 XAML如何使用數據類型的長度來設置我的UI文本框的MaxLength?根據在Linq中綁定的字段設置Windows Phone TextBox的MaxLength到SQL

我真的不想在我的UI代碼中固定長度,所以如果我的模式發生變化,我必須記住要在兩個位置更改它。

我99%肯定,如果我的文本框內置控件或從Telerik構建它沒有區別。

LINQ到SQL領域:

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Title", DbType = "NVarChar(50)", UpdateCheck = UpdateCheck.Never)] 
public string Title 
{ 
    get 
    { 
     return this._Title; 
    } 
    set 
    { 
     if ((this._Title != value)) 
     { 
      this.OnTitleChanging(value); 
      this.SendPropertyChanging(); 
      this._Title = value; 
      this.SendPropertyChanged("Title"); 
      this.OnTitleChanged(); 
     } 
    } 
} 

的Windows Phone 8 XAML:

<telerikPrimitives:RadTextBox x:Name="titleTextBox" Header="Title" 
           MaxLength="50" 
           HeaderStyle="{StaticResource HeaderAccentStyle}" 
           Text="{Binding Title, Mode=TwoWay}" Grid.Row ="0"/> 

我已經看過幾個WPF的答案,但他們使用不存在於WP行爲。

回答

0

不確定它是否適用於您的情況,但您可以創建屬性名稱的Dictionary作爲Length值並將它們綁定到Xaml中。

在這個例子中,我只是用DefaultValueAttribute,因爲我沒有這個System.Data.Linq.Mapping.ColumnAttribute但同樣的想法將工作

private Dictionary<string, int> _maxlengthValues; 
    public Dictionary<string, int> MaxLengthValues 
    { 
     get 
     { 
      if (_maxlengthValues == null) 
      { 
      // horrible example, but does the job 
      _maxlengthValues = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) 
        .ToDictionary(n => n.Name, p => p.GetCustomAttributes(typeof(DefaultValueAttribute), false)) 
        .Where(p => p.Value != null && p.Value.Any() && (p.Value[0] as DefaultValueAttribute).Value != null) 
        .ToDictionary(k => k.Key, v=>(int)(v.Value[0] as DefaultValueAttribute).Value); 
      } 
      return _maxlengthValues; 
     } 
    } 


    [DefaultValue(20)] // 20 char limit 
    public string TestString 
    { 
     get { return _testString; } 
     set { _testString = value; NotifyPropertyChanged("TestString"); } 
    } 

的XAML:

<TextBox Text="{Binding TestString}" MaxLength="{Binding MaxLengthValues[TestString]}" />