删除用户控件的代码背后有使用MVVM(Removing UserControl code behin

2019-10-19 05:56发布

我试图创建一个使用MVVM用户控制。 基本上我试图总结一个组合框,将来自程序存储库中提取数据。 这将允许我使用同样的组合框在我的应用程序很多不同的意见。 会有很多在整个应用程序的包裹组合框的。

我可以非常容易地创建使用的DependencyProperty和代码背后的控制。 我现在想将其转换为MVVM时遇到了问题搞清楚如何从视图模型中获得的价值回/在绑定到我的下拉框所在的视图。

任何意见或建议,此时将不胜感激。

谢谢,埃里克

Answer 1:

它是完全可以接受的使用UserControl使用MVVM时在它后面具有代码。 如果你真的想搬出的功能, UserControl ,然后将其移动到哪个父视图模式将要求它。 如果你不希望在几个地方重复相同的代码,你可以在一个类封装,并添加类的实例作为属性到每个相关视图模型。



Answer 2:

如果你有一个视图模型,将来自程序存储库中提取数据 - 您可以使用许多不同的ViewModels同一视图模型在你的应用程序:)

如果你使用一个DataTemplate你的看法知道如何呈现这个视图模型

 <DataTemplate DataType="{x:Type local:MyPullDataViewmodel}">
   <view:MyCoolPullDataShowComboboxUserControl />
 </DataTemplate>


Answer 3:

这是很容易的。

比方说,你有:

MyUserControlView.xaml

MYUserControlViewModel.cs

MyMainWindowView.xaml -为了您的主窗口视图(包含一个UserControl

MyMainWindowViewModel.cs -您的主窗口视图模型。

而你要绑定List<string> MyListToBind和离开代码隐藏完全是空的。

MyUserControlViewModel.cs

public class MyUserControlViewModel
{
private List<string> _MyListToBind;
public List<string> MyListToBind { get; set;}
}

MyMainWindowViewModel.cs

public class MyUserControlViewModel
{
private MyUserControlViewModel _MyControlViewModel;
public MyUserControlViewModel MyControlViewModel { get; set;}
}

MyMainWindowView.xaml

<Window ...
xmlns:my="clr-namespace:NamespaceContainingYourUserControlView>
<my:MyUserControlView DataContext = "{Binding Path= MyControlViewModel}"/>
</Window>

MyUserControlView.xaml

<UserControl ...>
<DataGrid ItemsSource = "{Binding Path= MyListToBind}" .../>
...
</DataGrid>
</UserControl>
  • 这不支持视图模型更新视图。 要做到这一点,您可以选择使用DependencyProperties为你做的,而不是正常的变量(像我一样),或使用INotifyPropertyChanged (谷歌,你会得到吨的例子)和OnPropertyChanged事件。
  • 你可能会在阅读起来DataTemplates他们在数据绑定非常有用。

你可以找到这个usefeul:

http://www.youtube.com/watch?v=BClf7GZR0DQ

我肯定是地狱没有! 祝好运。



文章来源: Removing UserControl code behind for use with MVVM