WPF常见问题

由 帅木 发布

1.Visual Studio 2022 报错: 当前上下文中不存在名称 ‘InitializeComponent’

如果错误存在但不影响正常运行,找到错误提示的那个文件,将 xxx.xaml 文件的属性更改为:,自定义工具会默认选中:MSBuild: Compile,如果已经是了,就切成其它,再改回来。


2.MVVM中,NotifyCanExecuteChangedFor无效

如果是这样写的:
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(MyCommand))]
public string username;

NotifyCanExecuteChangedFor不会调用你的命令,它只会导致命令发出其CanExecuteChanged事件信号,如果你想在username发生变化时运行代码,只需执行以下操作:
[ObservableProperty]
public string username;

partial void OnUsernameChanged(string value)
{
// TODO: do stuff here
}
注意:分部函数的名称规则是 On-变量名称首字母大写-Changed
参考:
https://stackoverflow.com/questions/73234760/notifycanexecutechangedfor-doesnt-execute-command-given-mvvm-community-toolkit
https://www.answeroverflow.com/m/1039952267069096006


3.Unable to cast object of type 'Microsoft.VisualStudio.XSurface.Wpf.WpfSurfaceApp' to type 'xxx.App'

因为 XAML 设计器在其自己的进程(WpfSurface.exe) 中运行,因此具有其自己的 Application 对象。
比如标记了:d: DataContext = "{d:DesignInstance vm:xxxViewModel,IsDesignTimeCreatable=True}" 且在xxxViewModel的无参构造函数里使用了App.Current就会有这个错误。
简单粗暴的解决方案就是不要在设计器进程使用Application,或者通过判断当前是否处在设计模式下,参考如下:
https://developercommunity.visualstudio.com/t/error-xdg0062-unable-to-cast-object-of-type-micros/1485738
https://stackoverflow.com/questions/425760/is-there-a-designmode-property-in-wpf



0条评论

评论已关闭