【问题标题】:Help on WPF Databinding to ViewModel Property (Prism)帮助 WPF 数据绑定到 ViewModel 属性(棱镜)
【发布时间】:2011-03-16 19:15:23
【问题描述】:

大家好, 希望有人有更新鲜的眼光,可以帮助我在这里查明问题,我正在尝试使用 prism 和 MVVM 模式创建一个小应用程序,到目前为止,一切都运行良好,我的命令与参数一起正常触发,但是,此处的 TextBlock 未按应有的方式从其视图模型绑定到 CurrentUserKey 属性。

有人有什么想法吗? 提前谢谢...

LoginView.xaml(为简洁起见,仅提供相关部分) ...

<Grid DataContext="{Binding Path=., Source={StaticResource viewModel}}">
  <Grid Margin="10">
    <Label  VerticalAlignment="Center" HorizontalAlignment="Right">Enter your Key:</Label>
    <TextBlock Name="txtUserKey" Text="{Binding Path=CurrentUserKey}" Margin="2" />

    <Button cal:Click.Command="{Binding GenericButtonClick}" cal:Click.CommandParameter="7">7</Button>
    <Button cal:Click.Command="{Binding GenericButtonClick}" cal:Click.CommandParameter="8">8</Button>
    <Button cal:Click.Command="{Binding GenericButtonClick}" cal:Click.CommandParameter="9">9</Button>
...
  </Grid>
...

LoginViewModel.cs

public class LoginViewModel : ViewModelBase
    {
        public LoginViewModel()
        {
            GenericButtonClick = new DelegateCommand<string>(GenericButtonClickHandler);
        }

        private void GenericButtonClickHandler(string argument)
        {
            if (argument.Length < 2) {
                CurrentUserKey += argument;
            }

            RaisePropertyChangedEvent("GenericButtonClick");
        }

        public string CurrentUserKey { get; set; }
        private ICommand GenericButtonClick { get; set; }
    }

ViewModelBase.cs

public class ViewModelBase:INotifyPropertyChanged   
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChangedEvent(string Property_name)
    {
        if (Property_name == null) return;

        PropertyChangedEventArgs e = new PropertyChangedEventArgs(Property_name);
        PropertyChanged(this, e);
    }
}

【问题讨论】:

  • 如果它没有绑定,您将在 Visual Studio 的“调试”窗口中获得一些与该效果相关的输出 - 您也可以将其粘贴到此处吗?
  • 对我的n00bness 感到抱歉,在“调试”窗口或“输出”窗口中?如果在调试窗口中,你能指定我应该看哪个对象吗?谢谢

标签: wpf data-binding mvvm prism prism-2


【解决方案1】:

当 CurrentUserKey 发生变化时,您没有提升 PropertyChanged。

此外,绑定到 TextBox 中的文本存在一些问题:请参阅 http://social.msdn.microsoft.com/forums/en-US/wpf/thread/c404360c-8e31-4a85-9762-0324ed8812ef/WPF: TextBox Text is not updating

【讨论】:

  • 感谢 Daniel 的回答,我现在将开始阅读有关文本框问题的内容,我认为它在此处引发了 PropertyChanged RaisePropertyChangedEvent("GenericButtonClick") 从 ViewModelBase 类中调用 PropertyChanged;不?超级可能我在这里遗漏了一些东西(我是一个总 n00b)
  • 您必须为已更改的属性提高 PropertyChanged。因此,在您的 CurrentUserKey 设置器中,您必须调用 RaisePropertyChangedEvent("CurrentUserKey");
  • aaaaaaaaaaaaaaargggghhhhh,你说得对,我养错了财产! (您也可以在 ExecuteMethodHandler 上提出它,但您的建议最好避免重复)...谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 2015-11-24
相关资源
最近更新 更多