我正在开发一个小程序,尝试使用DataTemplate跟踪MVVM方法,为我的VM创建视图。我遇到的问题是,不是创建视图的实例,而是显示VM的ToString()结果。如果我在View类(MainNavigation.xaml)的构造函数上放置一个断点,它永远不会到达。
以下代码,非常感谢。
MainWindow.xaml
<Window x:Class="Tester.Wpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Tester.Wpf"
xmlns:scr="clr-namespace:Tester.Wpf.Screens"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="x:Type scr:MainNavigationViewModel">
<scr:MainNavigation />
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Name="MainNav" Content="{Binding MainNavigationViewModel2}" />
</Grid>
</Window>
MainWindow.xaml.cs
using System.ComponentModel;
using System.Windows;
using Tester.Wpf.Screens;
namespace Tester.Wpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private MainNavigationViewModel _mainNavigationViewModel;
public MainWindow()
{
this.DataContext = this;
this.MainNavigationViewModel2 = new MainNavigationViewModel();
InitializeComponent();
}
public MainNavigationViewModel MainNavigationViewModel2
{
get { return _mainNavigationViewModel; }
set { _mainNavigationViewModel = value;
RaisePropertyChangedEvent("MainNavigationViewModel2");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainNavigation.xaml.cs
using System.Windows.Controls;
namespace Tester.Wpf.Screens
{
/// <summary>
/// Interaction logic for MainNavigation.xaml
/// </summary>
public partial class MainNavigation : UserControl
{
public MainNavigation()
{
InitializeComponent();
}
}
}
MainNavigationViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tester.Wpf.Helpers;
namespace Tester.Wpf.Screens
{
public class MainNavigationViewModel : BaseViewModel
{
public int Test = 10;
}
}
MainNavigation.xaml
<UserControl x:Class="Tester.Wpf.Screens.MainNavigation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Tester.Wpf.Screens"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Background="Blue">
<TextBlock>YOU"VE MADE IT!</TextBlock>
</Grid>
</UserControl>
答案 0 :(得分:5)
在MainWindow.xaml文件中,根据Sinatr的评论更改了以下行:
<DataTemplate DataType="x:Type scr:MainNavigationViewModel">
到
<DataTemplate DataType="{x:Type scr:MainNavigationViewModel}">