gpt4 book ai didi

c# - 如何将 UserControl 中的 DependencyProperty 绑定(bind)到 DataContext 属性? Windows 应用商店

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:22 24 4
gpt4 key购买 nike

我有一个具有依赖属性的 UserControl:

 public static readonly DependencyProperty Step2CommandProperty =
DependencyProperty.Register("Step2Command", typeof(ICommand), typeof(MyTripNavigationStep), new PropertyMetadata(null));

public ICommand Step3Command
{
get { return (ICommand)GetValue(Step3CommandProperty); }
set { SetValue(Step3CommandProperty, value); }
}

然后我有一个带有 ICommand 属性的 ViewModel:

  public ICommand SaveStep1Command
{
get
{
return new RelayCommand(() =>
{


});

}
}

然后我在页面中像这样绑定(bind)两个属性,其中我将 viewModel 作为 DataContext 和 UserControl。

            <UserControls:Step Step3Command="{Binding SaveStep1Command, Mode=OneWay}" />

未应用绑定(bind),userControl 中的 Step3Command 始终显示为 null。我知道 DataContext 工作正常,并且 Visual Studio 不允许我进行 TwoWay 绑定(bind)。我正在使用 GalaSoft Simple Mvvm 和 Visual Studio CTP 更新 2。

有人知道我做错了什么吗?谢谢。

最佳答案

您定义的属性有误。每次访问属性时都会调用 get block ,因此每次您(或 WPF 中的 MVVM 魔法)访问 SaveStep1Command 时都会创建一个新命令。这不是您想要的。

像这样重写属性:

在你的构造函数代码中,写:

SaveStep1Command = new RelayCommand(...)

然后像这样定义你的属性:

public ICommand SaveStep1Command { get; }

如果您使用的是旧版本的 .net/C#,则必须这样定义它:

public ICommand SaveStep1Command { get; private set; }

解释尝试:可能是数据绑定(bind)只创建了弱引用。使用您定义 SaveStep1Command 的方式,一旦设置了绑定(bind),它就会被创建,然后它就“躺在”堆上——下次 GC 启动时,空间就会被释放因为它没有强引用。

关于c# - 如何将 UserControl 中的 DependencyProperty 绑定(bind)到 DataContext 属性? Windows 应用商店,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840711/

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