Behaviorを使用して、TextBox をバインドされたプロパティの検証属性 (存在する場合) に接続しました。動作は次のようになります。
/// <summary>
/// Set the maximum length of a TextBox based on any StringLength attribute of the bound property
/// </summary>
public class RestrictStringInputBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
AssociatedObject.Loaded += (sender, args) => setMaxLength();
base.OnAttached();
}
private void setMaxLength()
{
object context = AssociatedObject.DataContext;
BindingExpression binding = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (context != null && binding != null)
{
PropertyInfo prop = context.GetType().GetProperty(binding.ParentBinding.Path.Path);
if (prop != null)
{
var att = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).FirstOrDefault() as StringLengthAttribute;
if (att != null)
{
AssociatedObject.MaxLength = att.MaximumLength;
}
}
}
}
}
ご覧のとおり、動作はテキスト ボックスのデータ コンテキストと、"Text" のバインディング式を取得するだけです。次に、リフレクションを使用して「StringLength」属性を取得します。使い方はこんな感じです。
<UserControl
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<TextBox Text="{Binding SomeProperty}">
<i:Interaction.Behaviors>
<local:RestrictStringInputBehavior />
</i:Interaction.Behaviors>
</TextBox>
</UserControl>
を拡張してこの機能を追加することもできますがTextBox
、ビヘイビアーはモジュラーであるため、ビヘイビアーを使用するのが好きです。