gpt4 book ai didi

c# - 在C#中从ViewModel中的View访问按钮

转载 作者:行者123 更新时间:2023-12-03 10:57:37 25 4
gpt4 key购买 nike

我正在尝试从View中的ViewModel访问按钮,但是由于出现错误,我丢失了一些东西:

Severity    Code    Description Project File    Line    Suppression State
Error CS1061 'MainWindow' does not contain a definition for 'Loadfile' and no extension method 'Loadfile' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?) Uml-Creator C:\Users\HH\Source\Repos\UMLEditor\Uml-Creator\Uml-Creator\View\MainWindow.xaml 54 Active

该按钮的目的是打开 OpenFileDialog。在我的 ViewModel中,我按如下方式处理点击:
class Load
{

private void Loadfile(object sender, EventArgs e)
{
OpenFileDialog loadfile = new OpenFileDialog();
if (loadfile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// File.Text = File.ReadAllText(loadfile.FileName);
}
}
}

和 View :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}

编辑:
<Button x:Name="openButton" ToolTip="Open project" Click="Load_Click">
<Image Source="pack://application:,,,/Images\Open.png" Stretch="UniformToFill" Height="17"></Image>
</Button>

最佳答案

MVVM体系结构中,View和ViewModel松散耦合。您应该像DelegateCommand这样使用Command并将View的DataContext设置为这样的ViewModel实例

public MainWindow()
{
InitializeComponent();
DataContext = new Load();
}

在XAML中执行类似的操作
<Button .... Click = "{Binding ClickCommand}" />

使用Nuget获取Prism软件包,并在Load类中,使用DelegateCommand之类的
public Load
{
public DelegateCommand<object> _clickCommand;
public DelegateCommand<object> ClickCommand
{
get
{
if (_clickCommand == null)
_clickCommand = new DelegateCommand<object>(OnClickCommandRaised);
return _clickCommand;
}
}

public void OnClickCommandRaised(object obj)
{
//Your click logic.
}
}

关于c# - 在C#中从ViewModel中的View访问按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975842/

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