如果我的Windows无法访问Application.Resources中定义的资源,那么Application.Resources的目的是什么?
这样做是有效的,我可以得到一个带有文本框的窗口,里面写着“Loki”...
App.xaml.cs:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ViewModel.ViewModel1 oVM = new ViewModel.ViewModel1 { Name = "Loki" };
MainWindow oVW = new MainWindow { Content = oVM };
oVW.ShowDialog();
}
}
MainWindow.xaml
<Window x:Class="TableGenerator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:TableGenerator.ViewModel"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type vm:ViewModel1}">
<TextBox Text="{Binding Path=Name}" />
</DataTemplate>
</Window.Resources>
<ContentPresenter />
</Window>
将DataTemplate从Window.Resources移动到Application.Resources并不起作用。当我运行这个程序时,窗口中没有文本框,但是有一些文本被显示出来,只是显示了我的视图模型类的名称,“TableGenerator.ViewModel.ViewModel1”。
App.xaml.cs没有改变。
MainWindow.xaml更改为:
<Window x:Class="TableGenerator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ContentPresenter />
</Window>
App.xaml:
<Application x:Class="TableGenerator.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:TableGenerator.ViewModel">
<Application.Resources>
<DataTemplate DataType="{x:Type vm:ViewModel1}">
<TextBox Text="{Binding Path=Name}" />
</DataTemplate>
</Application.Resources>
</Application>
为什么它不会在Application.Resources中查找我的DataTemplate?
ContentControl
而不是ContentPresenter
了吗? - Mike Eason