我试图将公共(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/