在XAML文件中定义Binding时如何使用自定义属性(属性字段是某个类静态变量)?答案是:在Path属性中使用如下格式:“(类名.属性名称)”。
背景
在使用WPF实现一个登录对话框时,有如下需求:
1)密码框需要在无输入时提示用户错误信息;
2)在所以输入都正确后,登录按钮才生效。
实现方法:
1)由于PasswordBox的Password不支持动态绑定通知,所以需要自己另外定义一个Password属性,并实现双向动态绑定。
属性定义:
public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper), new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
自定义的属性必须使用RegisterAttached注册为附加属性,这样才能在PasswordBox定义中直接引用。
XAML定义:
<PasswordBox x:Name="PasswordTextBox" HorizontalAlignment="Left" Height="23" Margin="249,228,0,0" VerticalAlignment="Top" Width="120">
<gui:PasswordBoxHelper.Password>
<Binding UpdateSourceTrigger="PropertyChanged" Path="Password" Mode="TwoWay">
<Binding.ValidationRules>
<validate:RequiredValidationRule ValidatesOnTargetUpdated="True"></validate:RequiredValidationRule>
</Binding.ValidationRules>
</Binding>
</gui:PasswordBoxHelper.Password>
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<AdornedElementPlaceholder Name="Adorned"></AdornedElementPlaceholder>
<TextBox Text="{Binding ElementName=Adorned, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" Margin="10,0,0,0" BorderBrush="Red" Foreground="Red" VerticalContentAlignment="Center" >
</TextBox>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</PasswordBox>
2)登录按钮的IsEnable属性需要使用MultiBinding,将多个输入框(用户名输入框、密码输入框等)的值校验条件转换成bool变量。当所有输入都校验正确时,IsEnable属性才会置为True。
XAML定义:
<Button x:Name="OkButton" Content="确定" HorizontalAlignment="Left" Margin="176,307,0,0" VerticalAlignment="Top" Width="97" Height="32" Click="OK_Button_Click" IsDefault="True">
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource OkButtonBindingConverter}">
<Binding ElementName="HostTextBox" Path="Text"></Binding>
<Binding ElementName="PortTextBox" Path="Text"></Binding>
<Binding ElementName="UsernameTextBox" Path="Text"></Binding>
<Binding ElementName="PasswordTextBox" Path="(gui:PasswordBoxHelper.Password)">
</Binding>
</MultiBinding>
</Button.IsEnabled>
</Button>
其中绑定自定义属性的关键部分为"(gui:PasswordBoxHelper.Password)",括号表示这是一个全限名定义的属性,不是链式属性。gui表示PasswordBoxHelper类在gui命名空间内。