首先是利用 ItemsControl 来随机(或者根据绑定传的值)来分布位置
主要是用Canvas来当画布, 然后由值来调整位置
首先,创建实体类
public class ClassA { public double UpTop{ get; set; } public double UpLeft{ get; set; } }
然后再你的ViewModel 调用
public class YourViewModel : INotifyPropertyChanged { private ObservableCollection<ClassA> yourList; public ObservableCollection<ClassA> YourList { get { return yourList; } set { yourList = value; OnPropertyChanged(nameof(YourList)); } } public YourViewModel() { // 初始化 YourList 并添加 ClassA 对象 YourList = new List<ClassA> { new ClassA { Top = 50, Left = 100 }, new ClassA { Top = 150, Left = 200 }, // 添加更多对象... }; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
下面是XAML代码:
<ItemsControl Background="DimGray" ItemsSource="{Binding YourList}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Background="Red" Text="YourContent" /> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Canvas.Top" Value="{Binding UpTop}"/> <Setter Property="Canvas.Left" Value="{Binding UpLeft}"/> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl>
这样就基本完成了, 这样加上通知后可以根据传值随时变更位置。
ObservableCollection 是什么 ,可以自己百度了解一下。标签:跟值,YourList,ClassA,set,排布,ObservableCollection,new,WPF,public From: https://www.cnblogs.com/falychen/p/17995841