【发布时间】:2012-12-05 11:13:49
【问题描述】:
我在 C# 中的 WPF 应用程序使用了 MVVM 模式。我定义了两个用户控件:
- 登录查看
- 项目视图
两个用户控件都添加到主窗口并使用相同的视图模型。 LoginView 包含一个PasswordBox,定义如下:
<PasswordBox Name="passwordBox" IsEnabled={Binding PasswordEnabled} />
ProjectsView 包含一个按钮,定义如下:
<Button Content="Login" Command="{Binding ProjectLoginCommand}" IsEnabled={Binding ProjectLoginEnabled}" CommandParameter="{Binding ElementName=passwordBox}" />
启动应用程序时,似乎无法绑定元素名称passwordBox。错误信息是:
Cannot find source for binding with reference 'ElementName=passwordBox' [...]
我该如何解决这个问题?
【问题讨论】:
-
为什么需要 PasswordBox 控件作为 CommandParameter?
-
点击按钮时我需要密码值(PasswordBox.Password)。但是,由于安全原因,无法直接绑定它。这就是为什么有几篇文章建议将完整的控件作为命令参数传递,然后访问 PasswordBox.Password。
-
为什么不试试下面的代码:PasswordBox s = sender as PasswordBox; ViewModel.Password = s.Password;对于 PasswordBox_PasswordChanged 事件处理程序
-
我只是想避免在代码隐藏中使用事件处理程序。
-
MVVM严格地说View和ViewModel应该单独工作。您不应访问 ViewModel 中的 View 元素。
标签: wpf mvvm binding commandparameter