【发布时间】:2015-03-15 17:43:51
【问题描述】:
如果我的窗口无法访问其中定义的资源,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 移动到 Application.Resources 而不是 Window.Resources 不起作用。当我运行它时,我得到一个窗口,根本没有 TextBox,但是以某种方式显示的文本只是说我的视图模型类的名称“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吗? -
我刚试了一下,使用 ContentControl 或 ContentPresenter 似乎没有任何区别。