我试图将窗口标题绑定到具有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的资源.
以下是View Model的代码:
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
解决方法
您可以尝试使用属性元素语法设置DataContext:
<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"> <Window.Resources> <vm:MainWindow x:Key="mainWindowviewmodel"/> </Window.Resources> <Window.DataContext> <StaticResourceExtension ResourceKey="mainWindowviewmodel"/> </Window.DataContext>
这应该在xaml解析器将在资源字典设置完成后执行StaticResourceExtension.
但是我认为甚至可以直接设置DataContext,而不将其声明为资源:
<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"> <Window.DataContext> <vm:MainWindow x:Key="mainWindowviewmodel"/> </Window.DataContext>