我有一個名爲ActionsTreeView用戶控件我建立MVVM的做法,我有一個IPluginsProvider接口,填充在我的用戶的數據。我希望能夠提供一個實現此接口的對象作爲初始化我的UserControl的ViewModel的參數。如何通過初始化參數,用戶控件在WPF(使用MVVM)
這裏是我的方法,到目前爲止,這是行不通的。我想知道我是否要走正確的道路?我在我的用戶控件中聲明瞭一個DependencyProperty
,這對我想要實例化此UserControl的mainWindow是可見的。該代碼只是試圖將PluginsProvider對象傳遞給我的UserControl,它需要它來構建它的ViewModel。
我PluginProvider DependencyProperty
在我的用戶二傳手我想我有正確的代碼,但不知道我要下去了正確的道路,什麼我從來沒有被擊中,因爲我的我的PropertyChanged
處理程序總是在MainWindow.xaml.cs空想錯過這個連接嗎?
ActionsTreeView.xaml.cs
public partial class ActionsTreeView: UserControl
{
public static readonly DependencyProperty PluginProviderProperty = DependencyProperty.Register("PluginProvider", typeof(Models.IPluginsProvider), typeof(ActionsTreeView), new FrameworkPropertyMetadata(null, OnPluginProviderChanged));
private ViewModels.ActionsTreeViewModel vm;
public ActionsTreeView()
{
//Wire-up our ViewModel with the data provider and bind it to DataContext for our user control
//This is a Mock-up until I figure out a way to get the real provider here
Models.IPluginProvider pluginSource = new Models.MockPluginProvider();
vm = new ViewModels.ActionsTreeViewModel(pluginSource);
this.DataContext = vm;
InitializeComponent();
}
private static void OnPluginProviderChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
((ActionsTreeView)source).PluginProvider = (Models.IPluginsProvider)e.NewValue;
}
public Models.IPluginsProvider PluginProvider
{
get
{
return (Models.IPluginsProvider)GetValue(PluginProviderProperty);
}
set
{
SetValue(PluginProviderProperty, value);
vm.SetPluginSource(PluginProvider);
}
}...
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
this.ActionProvider = new Models.PluginsProvider(Library.Action.AvailableActions);
}
private Models.IPluginsProvider _actionProvider;
public Models.IPluginsProvider ActionProvider
{
get { return _actionProvider; }
set
{
_actionProvider = value;
OnPropertyChanged("ActionProvider");
}
}
protected void OnPropertyChanged(string property)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) //HANDLER IS ALWAYS NULL
{
handler(this, new PropertyChangedEventArgs(property));
}
}
}
在MainWindow.xaml使用我的用戶
<Grid>
<UserControls:ActionsTreeView PluginProvider="{Binding ActionProvider}" />
</Grid>
一個公共屬性也可以工作,它設置datacontext。 – CRice