我正在尝试将窗口标题绑定到具有Title属性的ViewModel。以下是MainWindow XAML:
<Window x:Class="MyProject.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:MyProject.ViewModel;assembly=MyProject.ViewModel"
Title="{Binding Path=Title}" Height="350" Width="525" DataContext="{Binding Source={StaticResource mainWindowViewModel}}">
<Window.Resources>
<vm:MainWindow x:Key="mainWindowViewModel"/>
</Window.Resources>
...
</Window>
当我尝试运行此代码时,出现以下异常:"在 'System.Windows.StaticResourceExtension' 上提供值引发了异常。" 行号和位置指向 DataContext 属性,内部异常说明 "找不到名为 mainWindowViewModel 的资源。"
下面是视图模型的代码:
namespace MyProject.ViewModel
{
public class MainWindow : INotifyPropertyChanged
{
#region Fields
private const string TitlebarPrefixString = "My Project";
private string title = TitlebarPrefixString;
public string Title {
get
{
return this.title;
} // End getter
set
{
this.title = value;
OnPropertyChanged("Title");
} // End setter
} // End property
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
} // End if
} // End method
public event PropertyChangedEventHandler PropertyChanged;
} // End class
} // End namespace
我的理论是,在尝试将标题绑定到属性之后,资源被加载。当抛出异常时,窗口的资源属性为空。
是否唯一的解决方案是在 Code Behind 中设置 DataContext?我可以让它工作,但我更喜欢保持在 XAML 中。