У меня есть TableModel, которая выглядит следующим образом:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
namespace TestPRL.Model
{
public class TableModel : INotifyPropertyChanged
{
public TableModel()
{
_Players = new ObservableCollection<Player>();
}
private string _Name;
public string Name
{
get { return _Name; }
set {
if (_Name!=value)
{
_Name = value;
RaisePropertyChanged("Name");
}
}
}
private string _Game;
public string Game
{
get { return _Game; }
set
{
if (_Game != value)
{
_Game = value;
RaisePropertyChanged("Game");
}
}
}
private ObservableCollection<Player> _Players;
public ObservableCollection<Player> Players
{
get { return _Players; }
set {
if (_Players!=value)
{
_Players = value;
RaisePropertyChanged("Players");
}
}
}
public void DeletePlayer()
{
_Players.Remove(_SelectedPlayer);
RaisePropertyChanged("Players");
}
private Player _SelectedPlayer;
public Player SelectedPlayer
{
get
{
return _SelectedPlayer;
}
set
{
if (_SelectedPlayer != value)
{
_SelectedPlayer = value;
Trace.WriteLine(_SelectedPlayer.Name);
RaisePropertyChanged("SelectedPlayer");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
public class Player : INotifyPropertyChanged
{
public enum StateEnum
{
Normal,
Waiting,
Playing,
Absent
}
private int _ID;
public int ID
{
get { return _ID; }
set
{
if (_ID != value)
{
_ID = value;
RaisePropertyChanged("ID");
}
}
}
private string _Name;
public string Name
{
get { return _Name; }
set
{
if (_Name != value)
{
_Name = value;
RaisePropertyChanged("Name");
}
}
}
private StateEnum _State;
public StateEnum State
{
get { return _State; }
set
{
if (_State != value)
{
_State = value;
RaisePropertyChanged("State");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
, затем просмотрите модель
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using TestPRL.Model;
using TestPRL.Classes;
using TestPRL.View;
namespace TestPRL.ViewModel
{
public class TableViewModel:INotifyPropertyChanged
{
public TableViewModel()
{
MyCommand = new RelayCommand(new Action<object>(MyCommand_Execute));
Tables = new ObservableCollection<TableModel>();
}
public ObservableCollection<TableModel> Tables { get; set; }
public void LoadTables()
{
TableModel TableModel1 = new TableModel();
TableModel1.Name = "1";
TableModel1.Game = "Game1";
TableModel1.Players.Add(new Player { ID = 1, Name = "Tim", State = Player.StateEnum.Normal });
TableModel1.Players.Add(new Player { ID = 2, Name = "Tom", State = Player.StateEnum.Absent });
TableModel1.Players.Add(new Player { ID = 3, Name = "Reese", State = Player.StateEnum.Playing });
TableModel1.Players.Add(new Player { ID = 4, Name = "Paula", State = Player.StateEnum.Normal });
TableModel TableModel2 = new TableModel();
TableModel2.Name = "2";
TableModel2.Game = "Game2";
TableModel2.Players.Add(new Player { ID = 1, Name = "Karen", State = Player.StateEnum.Normal });
TableModel2.Players.Add(new Player { ID = 2, Name = "Summer", State = Player.StateEnum.Playing });
TableModel2.Players.Add(new Player { ID = 3, Name = "Willy", State = Player.StateEnum.Absent });
TableModel2.Players.Add(new Player { ID = 4, Name = "Mike", State = Player.StateEnum.Waiting });
TableModel2.Players.Add(new Player { ID = 4, Name = "Peter", State = Player.StateEnum.Waiting });
Tables.Add(TableModel1);
Tables.Add(TableModel2);
}
private ICommand _MyCommand;
public ICommand MyCommand
{
get { return _MyCommand; }
set { _MyCommand = value; }
}
private void MyCommand_Execute(object sender)
{
var myView = sender as TableView;
myView?.Test();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
и представление:
<UserControl x:Class="TestPRL.View.TableView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:rootns="clr-namespace:TestPRL"
xmlns:local="clr-namespace:TestPRL.View"
xmlns:classes="clr-namespace:TestPRL.Classes"
xmlns:viewmodel="clr-namespace:TestPRL.ViewModel"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Name="TablesGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<StackPanel HorizontalAlignment="Left">
<ItemsControl ItemsSource="{Binding Tables}" x:Name="MyTables">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="0" Margin="5">
<StackPanel Orientation="Vertical" Margin="6">
<Label Content="{Binding Name}" Foreground="Black" FontSize="16" FontWeight="Bold" Background="Transparent" BorderThickness="0"/>
<ListBox Name="PlayerListbox" ItemsSource="{Binding Players}" SelectedItem="{Binding DataContext.SelectedPlayer, RelativeSource={RelativeSource AncestorType=UserControl}}" IsSynchronizedWithCurrentItem="True" Background="#33A2A2A2" Foreground="White" BorderThickness="0" FontWeight="Bold" FontSize="12" Margin="0,15,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name = "TextControl" Text="{Binding Name}" Background="Transparent" Padding="4">
<TextBlock.Style>
<Style TargetType = "TextBlock" >
<Style.Triggers >
<DataTrigger Binding="{Binding State}" Value="Playing">
<Setter Property = "Foreground" Value="Blue"/>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="Waiting">
<Setter Property = "Foreground" Value="Gray"/>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="Absent">
<Setter Property = "Foreground" Value="#FF0097FF"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu DataContext="{Binding Path=DataContext, Source={x:Reference TablesGrid}}">
<MenuItem Header="Delete player" Command="{Binding MyCommand}" CommandParameter="{Binding}"/>
<MenuItem Header="Set player state to playing"/>
<MenuItem Header="Set player state to absent"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
MainWindow.xaml:
<Window x:Class="TestPRL.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestPRL"
xmlns:view = "clr-namespace:TestPRL.View"
xmlns:viewmodel ="clr-namespace:TestPRL.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
</Window.Resources>
<Grid>
<view:TableView x:Name="TableViewControl" Loaded="TableViewControl_Loaded"/>
</Grid>
</Window>
и файл MainWindow.xaml.cs, где я устанавливаю текст данных:
using System.Windows;
namespace TestPRL
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TableViewControl_Loaded(object sender, RoutedEventArgs e)
{
TestPRL.ViewModel.TableViewModel TableViewModel = new ViewModel.TableViewModel();
TableViewControl.DataContext = TableViewModel;
TableViewModel.LoadTables();
}
}
}
Элемент управления отображает все данные так, как я хочу, но я не знаю, какизменить / удалить выбранного игрока с помощью контекстного меню.
Как я могу получить правильный текст данных (Таблица и собственность игроков) для редактирования или удаления игрока?
Есть ли у кого-нибудь мысли о правильном направлении для меня?
Заранее спасибо, с наилучшими пожеланиями,
Flo