在 WPF 中,PasswordBox.Password 不是 DP,所以我们不能直接在 ViewModel 中绑定它。网上搜了一下,使用了这个方法,但是只是在加载视图的时候调用了一次转换器,所以ExecuteMyCommand中的参数为null:
主窗口.xaml
<DockPanel x:Name="WindowLayout" LastChildFill="False">
<Grid DockPanel.Dock="Top" Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="PasswordBox1" VerticalAlignment="Center"/>
<PasswordBox x:Name="PswBox" Grid.Column="1" Height="27"/>
<TextBlock Text="PasswordBox2" VerticalAlignment="Center" Grid.Row="1"/>
<PasswordBox x:Name="AgainPswBox" Grid.Column="1" Grid.Row="1" Height="27"/>
</Grid>
<Button IsDefault="True" Command="{Binding MyCommand}" DockPanel.Dock="Top" Content="Click" Width="60" Margin="10">
<Button.CommandParameter>
<MultiBinding Converter="{cvt:PlainMultiValueConverter}">
<Binding ElementName="PswBox"/>
<Binding ElementName="AgainPswBox"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
</DockPanel>
</Window>
转换器\PlainMultiValueConverter.cs
namespace MVVM_Light_Base.Converters
{
[MarkupExtensionReturnType(typeof(PlainMultiValueConverter))]
//[ValueConversion(typeof(object[]), typeof(object))]
public class PlainMultiValueConverter : MarkupExtension,
IMultiValueConverter
{
public static PlainMultiValueConverter converter = null;
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null == converter)
{
converter = new PlainMultiValueConverter();
}
return converter;
}
public object Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
return values;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
ViewModel\MainViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Windows.Controls;
namespace MVVM_Light_Base.ViewModel
{
public class MainViewModel : ViewModelBase
{
private RelayCommand<object> myCommand;
public RelayCommand<object> MyCommand
{
get
{
return myCommand ?? (myCommand =
new RelayCommand<object>(ExecuteMyCommand));
}
}
private void ExecuteMyCommand(object parameter)
{
var pswBoxes = parameter as object[];
PasswordBox pb;
string psw0;
string psw1;
try
{
pb = pswBoxes[0] as PasswordBox;
psw0 = pb.Password;
pb = pswBoxes[1] as PasswordBox;
psw1 = pb.Password;
}
catch
{
return;
}
}
}
}
为什么转换器不能完美工作?我该怎么办?