gpt4 book ai didi

c# - ICommand 依赖属性

转载 作者:太空狗 更新时间:2023-10-30 00:10:17 25 4
gpt4 key购买 nike

我有一个 UserControl,里面有一个按钮。此按钮需要将一些项目添加到所述 UC 内的网格中。我知道我可以通过 Click 事件来做到这一点。

这里的问题是我正在使用 MVVM,并且在相应的 ViewModel 之外更改数据会破坏格式(可以这么说)。

有没有办法创建一个 ICommand 依赖属性,这样我就可以将所述 DP 绑定(bind)到按钮,并具有将项目添加到我的 ViewModel 中的网格的功能? (我已经在我的 UC 和我的 ViewModel 中有了这个列表,它们按预期工作)

谢谢。

最佳答案

按照我尝试的方式找到了解决问题的方法。在这里留下答案,以便人们可以使用它:

1) 在您的用户控件的代码隐藏中,创建一个依赖属性。我选择 ICommand,因为在我的 ViewModel 中我将它设置为 DelegateCommand:

public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(UserControl));

public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}

set
{
SetValue(CommandProperty, value);
}
}

2) 在您的 UserControl 的 XAML 代码中,绑定(bind)此依赖属性(在本例中为按钮):

<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">

<Button Command="{Binding Command}" />

</Grid>

3) 接下来,在您的 ViewModel 上,声明一个 Command 属性并进行相应配置:

public ICommand ViewModelCommand { get; set; }

public ViewModelConstructor()
{
ViewModelCommand = new DelegateCommand(ViewModelCommandExecute);
}

private void ViewModelCommandExecute()
{
// Do something
}

4) 最后,在嵌套了 UserControl 的 View 上,我们声明绑定(bind):

<UserControls:UserControl Command={Binding ViewModelCommand}/>

这样,绑定(bind)就会发生,您可以在不破坏 MVVM 的情况下将来自任何用户控件按钮的命令绑定(bind)到您的 ViewModel。

关于c# - ICommand 依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com