WPF 列表內容跟值來排布位置
首先是利用 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 是什么 ,可以自己百度了解一下。

浙公網安備 33010602011771號