我試圖將窗口標題綁定到具有Title屬性的ViewModel。下面是主窗口XAML:WPF將窗口標題綁定到ViewModel屬性
<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中。
如果適用,您可以隨時將您的虛擬機資源移動到app.xaml。在旁註中,請將VM類命名爲「SomethingViewModel」,而不僅僅是與View相同的名稱,並使用命名空間來區分類。這只是非常奇怪和怪異的 – Viv
喬希史密斯有一個這樣的例子,我會看看如果我可以找到它,基本上當數據模板應用在XAML標題應用太.. –