gpt4 book ai didi

c# - Windows 窗体到 WPF MVVM

转载 作者:行者123 更新时间:2023-12-03 10:53:47 26 4
gpt4 key购买 nike

我正在使用 MVVM 模式和绑定(bind)将代码从 Windows 窗体重构为 WPF。

我的 Windows 窗体代码:

searchCriteriaListBox.Items.Add("Cat");

我的 WPF XAML:
<ListBox Height="288" HorizontalAlignment="Left" Margin="18,206,0,0" VerticalAlignment="Top" Width="1042" />

如何使用 WPF 绑定(bind)实现相同的“添加”操作?

最佳答案

将 Page/Window/UserControl(根级别的)的 DataContext 设置为 ViewModel。

创建房产 Items在 View 模型中。

使用以下作为 searchCriteriaListBox 的绑定(bind)

 {Binding Items, Mode=TwoWay}

<ListBox ItemsSource="{Binding Items, Mode=TwoWay}" Height="288" HorizontalAlignment="Left" Margin="18,206,0,0" VerticalAlignment="Top" Width="1042" />

在 View 模型中,放置一个 AddItemCommand。

在 AddItemCommand.Execute 中,将项目添加到 Items 集合

使用 MVVM Light对于一些可重复使用的项目,请阅读 WPF Apps With The Model-View-ViewModel Design Pattern

关于c# - Windows 窗体到 WPF MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11228142/

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