c# - 将一个类中的数据传递给另一个类中的函数

标签 c# wpf mvvm

我试图将公共(public)字符串的值传递给另一个类,该类包含一个在我按下 wpf 应用程序上的按钮时运行命令的函数。代码是:

class SearchViewModel : ObservableObject
{
    private string _SearchValue;
    public string SearchValue
    {
        get
        {
            return _SearchValue;
        }
        set
        {
            _SearchValue = value;
            RaisePropertyChange("SearchValue");
        }
    }

    public LaptopAsset Laptop { get; } = new LaptopAsset();

    private ICommand mUpdater;
    public ICommand UpdateCommand
    {
        get
        {
            if (mUpdater == null)
                mUpdater = new Updater(Laptop, SearchValue);
            return mUpdater;
        }
        set
        {
            mUpdater = value;
        }
    }
}

似乎 _SearchValue 或 SearchValue 从未从绑定(bind)的 WPF 控件传递:
<TextBox HorizontalAlignment="Left" Height="23" Margin="276,128,0,0" TextWrapping="Wrap" Text="{Binding SearchValue}" VerticalAlignment="Top" Width="120"/>

即使它下面的文本 block 已设置为查看相同的值:
<TextBlock HorizontalAlignment="Left" Height="23" Margin="276,156,0,0" TextWrapping="Wrap" Text="{Binding SearchValue}" VerticalAlignment="Top" Width="120"/>

因此,当我输入一个值并按 Tab 键时,它会更新文本 block 。但是,当我按下按钮时,该值不会传递给 mUpdater。我已将代码设置为 MessageBox.Show 传递的字符串的值。它只显示一个空消息框(表示空值)。

为什么不通过呢?更新程序代码如下所示:
public string SV;
private readonly LaptopAsset laptop;

public Updater(LaptopAsset laptop, string sv)
{
    this.laptop = laptop;
    this.SV = sv;
}

Grid DataContext 设置如下:
<Grid.DataContext>
    <ViewModels:SearchViewModel/>
</Grid.DataContext>

最佳答案

在附加 DataContext/ViewModel (SearchViewModel) 后, View 会调用 UpdateCommand getter。在那一刻,SearchValue 当然仍然为空,因此 Updater.SV 也设置为空。

相反,由于 Updater 实现了 ICommand,因此您可以更改 View 以将 CommandParameter 添加到 Button:

Command="{Binding UpdateCommand}" CommandParameter="{Binding SearchValue}"

然后,在 Updater 的 Execute 方法中,参数对象将是 SearchValue 字符串。
public void Execute(object parameter)
{
    string searchString = (string)parameter;
    // do something ...
}

试试看,让我知道!

关于c# - 将一个类中的数据传递给另一个类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201616/

相关文章:

c# - XSS 改变 ASP.NET session 状态

c# - 使用带有 IoC 容器的 Caliburn.Micro MVVM 框架的 Bootstrap 设计模式

c# - 如何添加动态文本作为任务栏图标覆盖?

c# - 如何在非模态对话框之上正确实现模态对话框?

c# - WPF应用程序-调用事件操作时不会触发监听方法

c# - 在现有模型对象之上实例化 ViewModels 和 Views

c# - Resharper 建议参数可以是 'BaseType' 类型

c# - WCF 服务不返回 GET 方法不允许的方法

c# - 如何启动将在任何编辑器中打开文本文件并自动将光标移动到特定行号的进程?

android - 如何通过改造解析 JSON 响应