根据Windows Phone TextBox在Linq to SQL中绑定到的字段设置其最大长度



我有很多由SQLMetal为我的WP Linq to SQL数据库创建的字段,这些字段的数据类型为nvarchar(##)。XAML中如何使用数据类型的长度来设置UI文本框的MaxLength?

我真的不想在我的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中不存在的行为。

不确定它是否适用于您的情况,但您可以创建一个属性名称和长度值的Dictionary,并将它们绑定到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]}" />

最新更新