Очень просто!
Вот вам пример.
XAML. Здесь идея в том, что для Binding'а на список элементов вам нужен ItemsControl
. А для расположения его как в UniformGrid
нужно переопределить ItemsPanel
:
<Window x:Class="SO8WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SO8WPF"
Title="Binding to uniform grid" Height="350" Width="525">
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" Rows="3" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Text}">
<Label.Background>
<SolidColorBrush Color="{Binding Color}"/>
</Label.Background>
</Label>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
Теперь view model. Мы берём стандартную имплементацию INPC, ничего особенного.
public class ItemVM : INotifyPropertyChanged
{
string text;
public string Text
{
get { return text; }
set { if (text != value) { text = value; NotifyPropertyChanged(); } }
}
Color color;
public Color Color
{
get { return color; }
set { if (color != value) { color = value; NotifyPropertyChanged(); } }
}
void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Кладём VM-ки в плоский список. Если реально нужна индексация с двумя индексами, делаем это отдельно.
class MainVM
{
public ObservableCollection<ItemVM> Items { get; } =
new ObservableCollection<ItemVM>()
{
new ItemVM() { Text = "Fünf", Color = Colors.Chocolate },
new ItemVM() { Text = "Sechs", Color = Colors.DarkSlateBlue },
new ItemVM() { Text = "Alte", Color = Colors.Maroon },
new ItemVM() { Text = "Hex", Color = Colors.LawnGreen },
new ItemVM() { Text = "Sieben", Color = Colors.DeepPink },
new ItemVM() { Text = "Acht", Color = Colors.Turquoise },
new ItemVM() { Text = "Gute", Color = Colors.Silver },
new ItemVM() { Text = "Nacht", Color = Colors.Orange }
};
public ItemVM this[int i, int j]
{
get { return Items[i * 3 + j]; }
set { Items[i * 3 + j] = value; }
}
}
App.xaml
делаем пустым, окно сначала оснащаем VM'кой, а показываем лишь потом:
<Application x:Class="SO8WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>
public partial class App : Application
{
MainVM mainVM = new MainVM();
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new MainWindow() { DataContext = mainVM }.Show();
}
}
Вуаля! У нас получилась вот такая картинка:

Для случая, когда с объектом по клику должно что-нибудь происходить, используются команды. Давайте сделаем, чтобы при клике объект перекрашивался в случайный цвет.
Для начала, нам нужна команда, то есть, имплементация ICommand
. Я реализую простейший вариант, но вам, возможно, понадобится что-нибудь более интеллектуальное. С SimpleCommand
можно привязать команду к вашей лямбде или методу.
class SimpleCommand : ICommand
{
private readonly Action onCommand;
public SimpleCommand(Action onCommand)
{
this.onCommand = onCommand;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
onCommand();
}
}
Далее, дополним ItemVM
командой и её реализацией:
public class ItemVM : INotifyPropertyChanged
{
// добавили общий генератор случайных чисел
static Random rnd = new Random();
public ItemVM()
{
// привязываем команду к методу OnActivation
Activate = new SimpleCommand(OnActivation);
}
string text;
public string Text
{
get { return text; }
set { if (text != value) { text = value; NotifyPropertyChanged(); } }
}
Color color;
public Color Color
{
get { return color; }
set { if (color != value) { color = value; NotifyPropertyChanged(); } }
}
// добавили свойство с командой, которая устанавливается в конструкторе
public ICommand Activate { get; }
void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
void OnActivation()
{
// меняем цвет на случайный
Color = Color.FromRgb(
(byte)rnd.Next(256), (byte)rnd.Next(256), (byte)rnd.Next(256));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Окей, VM-часть в порядке. Теперь нужно прикрутить команду к клику. Делается это так.
Во-первых, нужно подключить nuget-пакет System.Windows.Interactivity.WPF
(как обычно, через правый клик по References → Manage NuGet Packages...). Имея это, модифицируем наш шаблон для элемента:
<Label Content="{Binding Text}">
<!-- привязываем команду Activate к событию MouseLeftButtonUp -->
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding Activate}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Label.Background>
<SolidColorBrush Color="{Binding Color}"/>
</Label.Background>
</Label>
В список пространств имён окна не забываем добавить
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Немного покликав, получаем перекрашенную картинку:
