Xan*_*ndr 4 c# wpf user-controls mvvm icommand
我有一个带有按钮的UserControl.此按钮需要将一些项添加到所述UC内部的网格中.我知道我可以用Click事件做到这一点.
这里的问题是我使用MVVM并在相应的ViewModel之外更改数据会破坏格式(可以这么说).
有没有办法创建一个ICommand依赖属性,所以我可以将所述DP绑定到按钮,并具有在ViewModel中将项添加到网格的功能?(我的UC和我的ViewModel中都有List,它们按预期工作)
谢谢.
Xan*_*ndr 12
找到了一种方法来解决它我想要的方式.在这里留下答案,以便人们可以使用它:
1)在用户控件的代码隐藏中,创建一个依赖属性.我选择ICommand,因为在我的ViewModel中我将其设置为DelegateCommmand:
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(UserControl));
public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}
set
{
SetValue(CommandProperty, value);
}
}
Run Code Online (Sandbox Code Playgroud)
2)在UserControl的XAML代码中,绑定此依赖项属性(在本例中为一个按钮):
<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<Button Command="{Binding Command}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)
3)接下来,在ViewModel上,声明一个Command属性并进行相应配置:
public ICommand ViewModelCommand { get; set; }
public ViewModelConstructor()
{
ViewModelCommand = new DelegateCommand(ViewModelCommandExecute);
}
private void ViewModelCommandExecute()
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
4)最后,在ViewControl嵌套的View上,我们声明绑定:
<UserControls:UserControl Command={Binding ViewModelCommand}/>
Run Code Online (Sandbox Code Playgroud)
这样,绑定将发生,您可以将命令从任何用户控件的按钮绑定到ViewModel,而不会破坏MVVM.
| 归档时间: |
|
| 查看次数: |
8560 次 |
| 最近记录: |