您没有共享足够的代码让我确定您正在尝试做什么。虽然在某些情况下您需要解析模板,但通常有更好的方法。所以这就是我在 MVVM 上下文中如何理解你的情况,你能这样做吗?
xml:
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type local:Test1ViewModel}">
<local:Test1View />
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding ContentModel}" />
</Grid>
测试1视图:
<UserControl x:Class="WpfApplication1.Test1View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBlock Text="{Binding Name}" Background="Beige" Padding="5" />
<TextBlock Text="{Binding Address}" Background="PeachPuff" Padding="5" />
</StackPanel>
</UserControl>
视图模型:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private Test1ViewModel _contentModel;
public Test1ViewModel ContentModel { get { return _contentModel; } set { _contentModel = value; OnPropertyChanged("ContentModel"); } }
public ViewModel()
{
this.ContentModel = new Test1ViewModel() { Name = "John Higgins", Address = "Wishaw" };
}
}
public class Test1ViewModel : INotifyPropertyChanged
{
private string _name;
public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } }
private string _address;
public string Address { get { return _address; } set { _address = value; OnPropertyChanged("Address"); } }
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}