在我的TextBoxs中,我绑定到dataRowView。我的约束关系是:
TextBox --binding-- DataRowView
或
TextBox --binding-- Property --binding-- DataRowView
有时候我不会直接创建TextBox和DataRowView。
我需要在TextBox中设置MaxLength。 在TextBox中使用WPF TextBox MaxLength -- Is there any way to bind this to the Data Validation Max Length on the bound field?设置MaxLength的第一个关系 但我发现了第二关系的问题。当我将TextBox绑定到属性和属性到DataRowView时,我不知道是什么找到了datarowView。
简单代码 - xaml:
<Window.Resources>
<l:Behaviors x:Key="BehaviorsStringInput" x:Shared="False">
<l:RestrictStringInputBehavior/>
</l:Behaviors>
<Style x:Key="tb" TargetType="{x:Type TextBox}">
<Setter Property="l:SupplementaryInteraction.Behaviors" Value="StaticResource BehaviorsStringInput}"/>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<TextBox x:Name="tb1" Text="{Binding ElementName=_this,Path=MyText}" Width="300" Height="20" Margin="10" Style="{StaticResource tb}"/>
<TextBox x:Name="tb2" Width="300" Height="20" Margin="10"/>
</StackPanel>
CS:
private DataRowView dr;
public static readonly DependencyProperty MyTextProperty;
//
//...
//
Binding bin = new Binding("TextValue");
bin.Source = dr;
bin.Mode = BindingMode.TwoWay;
tb.SetBinding(TextBox.TextProperty, bin);
Binding bin2 = new Binding("TextValue");
bin2.Source = dr;
bin2.Mode = BindingMode.TwoWay;
this.SetBinding(MainWindow.MyTextProperty, bin);
RestrictStringInput:
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)
{
if (context is DataRowView)
{
DataRowView drv = (DataRowView)context;
// bingin.ParentBinding.Path.Path for tb1 has TextValue value and is correct, but for tb2 value is MyText.
DataColumn dc = drv.Row.Table.Columns[binding.ParentBinding.Path.Path];
if (dc != null)
{
AssociatedObject.MaxLength = dc.MaxLength;
}