gpt4 book ai didi

c# - 如何在此模型中应用 MVVM 模式?

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:32 25 4
gpt4 key购买 nike

问题从这篇文章开始:Using binding to a List<UserControl> how can I do for not showing the controls

我正在设计这样的东西:

List<Container>
(Below container properties)
- Objective: string
- Problems: List<ProblemUserControl>

ProblemUserControls 是一个 UserControl,其中包含一个名为 Problem 的额外属性。但是上面的帖子有人建议我使用 MVVM 模式。我正在调查,但我仍然感到困惑,或者我需要一些帮助来理解 WPF 中的模式。

最佳答案

下面是一个例子来说明如何使用 MVVM。请注意,不需要有用户控件列表,实际上从 MVVM 的角度来看,这会被认为是不正确的。

这基于 Visual Studio 中的默认 WPF 应用程序模板。

这里是涉及到的类。

public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null)
{
changed(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class Container : ViewModelBase
{
private string m_Objective;
private ProblemCollection m_Problems;

public Container()
{
m_Problems = new ProblemCollection();
}

public string Objective
{
get { return m_Objective; }
set
{
m_Objective = value;
OnPropertyChanged("Objective");
}
}

public ProblemCollection Problems
{
get { return m_Problems; }
set
{
m_Problems = value;
OnPropertyChanged("Problems");
}
}
}

public class Problem : ViewModelBase
{
private string m_Name;

public string Name
{
get { return m_Name; }
set
{
m_Name = value;
OnPropertyChanged("Name");
}
}
}

public class ProblemCollection : ObservableCollection<Problem>
{
}

还有主窗口。请注意,我已注释掉您的矩形以显示绑定(bind)

<Window x:Class="StackOverflowDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock TextWrapping="Wrap" Text="{Binding Objective}" Grid.Column="0" VerticalAlignment="Center"
FontWeight="Bold" />
<ItemsControl ItemsSource="{Binding Problems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--<Rectangle Stroke="Black" Height="20" Width="20" Margin="1,0" />-->
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>

主窗口.cs

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Create dummy test data.
// Normally this will be passed to the window or set externally
var container = new Container();
container.Problems.Add(new Problem {Name = "Foo"});
container.Problems.Add(new Problem {Name = "Bar"});
container.Problems.Add(new Problem {Name = "hello"});
container.Problems.Add(new Problem {Name = "world"});

DataContext = container;
}
}

关于c# - 如何在此模型中应用 MVVM 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7311747/

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