【发布时间】:2013-06-05 16:30:00
【问题描述】:
我正在尝试将 Window Title 绑定到具有 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
我的理论是在尝试将标题绑定到属性之后加载资源。抛出异常时,Window 的 Resources 属性为空。
是唯一的解决方案是在后面的代码中设置 DataContext 吗?我可以让它工作,但我更愿意将它保存在 XAML 中。
【问题讨论】:
-
如果适用,您始终可以将您的 VM 资源移动到 app.xaml。在旁注中,请将 VM 类命名为
SomethingViewModel,而不仅仅是与 View 相同的名称,并使用命名空间来区分类。这真的很奇怪和怪异 -
Josh Smith 有一个这样的例子,我会看看我能不能找到它,基本上当在 XAML 中应用数据模板时,标题也被应用了..
标签: c# wpf data-binding mvvm