WPF TextBox MaxLength — Is there any way to bind this to the Data Validation Max Length on the bound field?

前端 未结 5 641
北海茫月
北海茫月 2020-12-14 23:27

ViewModel:

public class MyViewModel
{
    [Required, StringLength(50)]
    public String SomeProperty { ... }
}

XAML:



        
5条回答
  •  Happy的楠姐
    2020-12-14 23:51

    The Markup extension is definitely the way to go. I am creating a subclass of BindingDecoratorBase called Binding which has a model DataType dependency property. As MarkupExtensions are created during InitializeComponent() there is no way to determine the DataContext as it will not have been set yet.

    Providing the model type permits reflective access to attributes defined on the model. This permits:

    • Setting MaxLength for TextBoxes.
    • Setting StringFormat for TextBlocks.
    • Setting the default Converter depending on member data type.
    • Adding required validation. Using either the binding's ValidationRules or by setting ValidatesOnDataErrors.

    The markup looks like: Text="{PO:Binding DataType=model:modAccount, Path=SubAccount}"

    Formatting, MaxLength, and Conversion rolled into one package with no need to change anything as the model classes change.

提交回复
热议问题