我正在启动WPF项目。试图通过viewmodel绑定usercontrol。其中viewmodel在Application.Reousrces中的DataTemplate处使用dataType定义。但是用户控件不绑定。有人可以帮助我吗?
<Application.Resources>
<DataTemplate DataType="{x:Type vm:MatterPanelViewModel}">
<uc:MatterPanel />
</DataTemplate>
</Application.Resources>
将绑定用户控件的主窗口。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:MyProject"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" x:Class="MyProject.MainWindow"
Title="MyProject" WindowState="Maximized" d:DataContext="{d:DesignInstance Type=uc:MainWindowViewModel}">
<Grid Grid.Row="2">
<ContentControl Content="{Binding CurrentViewModel}" Margin="10,0,10,10" />
</Grid>
</Window>
CurrentViewModel是MainViewModel的属性。
public class MainWindowViewModel:ViewModelBase
{
private ViewModelBase _currentViewModel;
public ViewModelBase CurrentViewModel
{
get { return this._currentViewModel; }
set
{
if(this._currentViewModel == value) { return; }
this._currentViewModel = value;
this.NotifyOfPropertyChange(() => this.CurrentViewModel);
}
}
public MatterPanelViewModel MatterPanelViewModel { get; set; }
public MainWindowViewModel()
{
this.MatterPanelViewModel = ServiceLocator.Current.GetService<MatterPanelViewModel>();
}
}
public class MatterPanelViewModel:ViewModelBase
{
public MatterPanelViewModel()
{
}
}
ViewModelBase在这里,
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged
{
add { this._propertyChanged += value; }
remove { this._propertyChanged -= value; }
}
private event PropertyChangedEventHandler _propertyChanged = delegate{ };
protected void NotifyOfPropertyChange<T>(Expression<Func<T>> property)
{
var lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if(lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
{
memberExpression = (MemberExpression)lambda.Body;
}
this.NotifyOfPropertyChange(memberExpression.Member.Name);
}
public void NotifyOfPropertyChange(string property)
{
this.RaisePropertyChanged(property, true);
}
private void RaisePropertyChanged(string property, bool verifyProperty)
{
var handler = this._propertyChanged;
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
}
答案 0 :(得分:1)
最后,我解决了这个问题。 viewmodel和usercontrol映射应在MainWindow下,但在主应用程序下。我只是从主应用编写代码
<Application.Resources>
<DataTemplate DataType="{x:Type vm:MatterPanelViewModel}">
<uc:MatterPanel />
</DataTemplate>
</Application.Resources>
到主窗口
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<DataTemplate DataType="{x:Type vm:MatterPanelViewModel}">
<usc:MatterPanel/>
</DataTemplate>
</Window.Resources>
然后运行良好。