【发布时间】:2021-02-27 18:25:01
【问题描述】:
在我的 WPF 应用程序中,我想使用 ObservableCollection 来包含一些 Wave 类。每个Wave 都有一个ObservableCollection 来包含一些Couple 类。它看起来像:
ObservableCollection<Wave> Waves { get; set; }
- int StartYear { get; set; }
- ObservableCollection<Couple> Couples { get; set; }
- int A { get; set; }
- int B { get; set; }
- some other Properties
添加Waves 后,int 属性运行良好。但是,每个Wave 中的Couples 都会在它们中的每一个都更改时更改。它们具有相同的 GUID。
每个Wave 中的Coupless 怎么可能不同?
这是我的代码:
// Couple.cs
public class Couple : DependencyObject
{
public int A { get { return (int)GetValue(AProperty); } set { SetValue(AProperty, value); } }
public int B { get { return (int)GetValue(BProperty); } set { SetValue(BProperty, value); } }
public static readonly DependencyProperty AProperty = DependencyProperty.Register("A", typeof(int), typeof(Couple), new PropertyMetadata(0));
public static readonly DependencyProperty BProperty = DependencyProperty.Register("B", typeof(int), typeof(Couple), new PropertyMetadata(0));
}
// Wave.cs
class Wave : DependencyObject
{
public ObservableCollection<Couple> Couples
{
get { return (ObservableCollection<Couple>)GetValue(CouplesProperty); }
set { SetValue(CouplesProperty, value); }
}
public static readonly DependencyProperty CouplesProperty = DependencyProperty.Register("Couples", typeof(ObservableCollection<Couple>), typeof(Wave), new PropertyMetadata(new ObservableCollection<Couple>()));
}
// XAML of the UserControl
<ItemsControl Grid.Column="1" ItemsSource="{Binding Waves}" ScrollViewer.HorizontalScrollBarVisibility="Visible" Margin="0,0,0,6" Focusable="False" ScrollViewer.CanContentScroll="False" VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Width="240">
<ItemsControl ItemsSource="{Binding Couples}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="01" TextAlignment="Center"/>
<TextBox Grid.Column="1" Text="{Binding A}"/>
<TextBox Grid.Column="2" Text="{Binding B}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我是 MVVM 的新手。以前,这些值是通过使用ListBox 的Items 属性获得的,但现在我想更改这些代码以适应MVVM 模式。谢谢!
【问题讨论】:
标签: c# wpf mvvm observablecollection itemscontrol