gpt4 book ai didi

wpf - 将 ObservableCollection 绑定(bind)到行

转载 作者:行者123 更新时间:2023-12-04 05:06:56 24 4
gpt4 key购买 nike

我想在我的 UserControl 中有一个图形部分,它将基于集合显示行(并在运行时更新坐标,并在运行时基于集合添加/删除行)。

假设我有一个名为 Class1 的类:

public class Class1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}

private int _x1 = 0;
public int X1
{
get { return _x1; }
set
{
_x1 = value;
OnPropertyChanged(new PropertyChangedEventArgs("X1"));
}
}
}

我的 UserControl 中有一个 ObservableCollection:
        public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}

private ObservableCollection<Class1> _classes = new ObservableCollection<Class1>();
public ObservableCollection<Class1> Classes
{
get { return _classes; }
}

如果我知道行数,我可以在我的 UserControl 中创建行数,如下所示:

XAML:
<Grid DataContext="{Binding ElementName=LayoutRoot}">
<Line X1="{Binding Items[0].X1}" X2="100" Y1="50" Y2="100" Stroke="Red" StrokeThickness="4"/>
<Line X1="{Binding Items[1].X1}" ... />
...
</Grid>

请问我该如何进行?

感谢您的任何努力

最佳答案

您可以使用 ItemsControl并创建一个 DataTemplate对于Class1反对并绑定(bind)您的 ObservableCollectionItemsControl .

使用 Canvas 可能也是一个好主意。作为 ItemsPanelTemplate如果你想在整个地方画线

这是一个简单的例子:

xml:

<Grid DataContext="{Binding ElementName=UI}">
<ItemsControl ItemsSource="{Binding Classes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Class1}">
<Line Stroke="Black" StrokeThickness="2" Fill="Black" X1="{Binding X1}" X2="{Binding X2}" Y1="{Binding Y1}" Y2="{Binding Y2}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>

代码:
public partial class MainWindow : Window
{

public MainWindow()
{
InitializeComponent();
Random ran = new Random();
for (int i = 0; i < 10; i++)
{
Classes.Add(new Class1 { X1 = ran.Next(0,100), Y1 = ran.Next(0,100), X2 = ran.Next(0,100), Y2 = ran.Next(0,100) });
}
}

private ObservableCollection<Class1> _classes = new ObservableCollection<Class1>();
public ObservableCollection<Class1> Classes
{
get { return _classes; }
}

}

结果:

enter image description here

关于wpf - 将 ObservableCollection 绑定(bind)到行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15426460/

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