MVVM and data binding to UniformGrid

I am trying to create the back of a WPF table with some rectangles. I use MVVM and I need rectangles of the same size. If defined via Xaml, this works with a fixed "BucketCount" 4:

<VisualBrush> <VisualBrush.Visual> <UniformGrid Height="500" Width="500" Rows="1" Columns="{Binding BucketCount}"> <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" /> <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/> <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/> <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/> </UniformGrid> </VisualBrush.Visual> <VisualBrush> 

How can I bind my ObservableCollection Rectangles? UniformGrid does not have an ItemsSource property. Do I need to use an ItemsControl? If so, how can I do this?

Thanks in advance.

+4
source share
1 answer

You can use ItemsControl for Bind like this. A simple example where ItemsSource is just an ObservableCollection<Brush>

 <VisualBrush> <VisualBrush.Visual> <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyBrushes}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Height="500" Width="500" Rows="1"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="{Binding}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </VisualBrush.Visual> </VisualBrush> 

Update
It works for my use case, but I might be missing something here. Here is the complete code I tried. I get the same result from both

MainWindow.xaml

 <Grid> <Grid.Background> <VisualBrush> <VisualBrush.Visual> <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyBrushes}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Height="500" Width="500" Rows="1"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="{Binding}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <!--<UniformGrid Height="500" Width="500" Rows="1" Columns="4"> <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" /> <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/> <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/> <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/> </UniformGrid>--> </VisualBrush.Visual> </VisualBrush> </Grid.Background> </Grid> 

MainWindow.xaml.cs

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); BrushConverter brushConverter = new BrushConverter(); MyBrushes = new ObservableCollection<Brush>(); MyBrushes.Add(brushConverter.ConvertFrom("#22ADD8E6") as Brush); MyBrushes.Add(brushConverter.ConvertFrom("#22D3D3D3") as Brush); MyBrushes.Add(brushConverter.ConvertFrom("#22ADD8E6") as Brush); MyBrushes.Add(brushConverter.ConvertFrom("#22D3D3D3") as Brush); this.DataContext = this; } public ObservableCollection<Brush> MyBrushes { get; set; } } 
+8
source

Source: https://habr.com/ru/post/1332830/


All Articles