class Anime
{
public string Name {get; set;}
public double Rating {get; set;}
public string Author {get; set;}
public string Serie {get; set;}
public string Url {get; set;}
}
class AnimeListViewModel
{
public ObservableCollection<Anime> AnimeList {get; set;} = new ObservableCollection<Anime>
{
new Anime { Name = "Наруто", Rating = 5, Author = "Масаси Кисимото"},
new Anime { Name = "Стальной алхимик", Rating = 5, Author = "Хирому Аракава"},
new Anime { Name = "X", Rating = 5, Author = "CLAMP"},
};
}
<Window ...
xmlns:app="clr-namespace:Anime">
<Window.DataContext>
<app:AnimeListViewModel/>
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding AnimeList}"
DisplayMemberPath="Name"/>
x:Name="AnimeListBox"/>
</Grid>
</Window>
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
public class EditPersonVm : BaseViewModel // который реализует INotifyPropertyChanged
{
private readonly Person _person;
public Person Person => _person;
private string _firstName;
public string FirstName
{
get => _firstName;
set { _firstName = value; RaisePropertyChanged(); }
}
private string _lastName;
public string LastName
{
get => _lastName;
set { _lastName= value; RaisePropertyChanged(); }
}
private string _middleName;
public string MiddleName
{
get => _middleName;
set { _middleName= value; RaisePropertyChanged(); }
}
public string InitFullName => $"{_person.LastName} {_person.FirstName[0]}. {_person.MiddleName[0]}.";
public RelayCommand OkButton { get; set; } = new RelayCommand(Save);
public EditPersonVm(Person person)
{
_person = person;
FirstName = person.FirstName;
LastName = person.LastName;
MiddleName = person.MiddleName;
}
private void Save()
{
//
}
}
<Window ...>
<StackPanel Orientation="Vertical">
<Label Content="Изначальное имя:"/>
<StackPanel>
<TextBlock Text="{Binding Person.LastName}"/>
<TextBlock> </TextBlock>
<TextBlock Text="{Binding Person.FirstName}"/>
<TextBlock> </TextBlock>
<TextBlock Text="{Binding Person.MiddleName}"/>
</StackPanel>
<Label Content="Фамилия:"/>
<TextBox Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}"/>
<Label Caption="Имя:"/>
<TextBox Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}"/>
<Label Caption="Отчество:"/>
<TextBox Text="{Binding MiddleName, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="OK" Command="{Binding OkCommand}">
</StackPanel>
</Window>
i:InvokeCommandAction
из System.Windows.Interactivity
.System.Windows.Interactivity
с помощью добавления ссылки (она в списке расширений).xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
i:EventTrigger
и i:InvokeCommandAction
:<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding KeyDownCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<ListBox ItemsSource="{Binding DevList}" SelectedItem="{Binding SelectedElement}" />
<GroupBox DataContext="{Binding SelectedElement}">
</GroupBox>
<GroupBox DataContext="{Binding SelectedElement.Subelement1}">
</GroupBox>
<Window x:Class="TestApp.MainWindow"
xmlns:testApp="clr-namespace:TestApp"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type testApp:TestInt}">
<TextBlock Text="{Binding Value}" Background="Red"/>
</DataTemplate>
<DataTemplate DataType="{x:Type testApp:TestStr}">
<TextBlock Text="{Binding Value}" Background="Yellow"/>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentControl Content="{Binding Test1}"/>
<ContentControl Content="{Binding Test2}"/>
<ListBox ItemsSource="{Binding TestList}"/>
</StackPanel>
</Window>
public class TestInt
{
public int Value { get; set; }
}
public class TestStr
{
public string Value { get; set; }
}
public partial class MainWindow : Window
{
public TestInt Test1 { get; set; }
public TestStr Test2 { get; set; }
public List<object> TestList { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Test1 = new TestInt { Value = 123 };
Test2 = new TestStr { Value = "asd" };
TestList = new List<object> { Test1, Test2 };
}
public class Item : BaseViewModel
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
RaisePropertyChanged();
}
}
private int _itemMode;
public int ItemMode
{
get => _itemMode;
set
{
_itemMode = value;
RaisePropertyChanged();
}
}
}
public class ItemsList
{
public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>
{
new Item { Name = "Один", ItemMode = 1 },
new Item { Name = "Два", ItemMode = 2 },
new Item { Name = "Три", ItemMode = 3 },
};
}
<Grid>
<Grid.Resources>
<converters:IntToBoolConverter x:Key="IntToBoolConverter"/>
<DataTemplate DataType="{x:Type viewModels:Item}">
<Border x:Name="Data">
<Grid x:Name="ContentBase" Margin="1,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Name="DisplayText" Grid.Column="0" Content="{Binding Name}"/>
<RadioButton Name="_1" Grid.Column="1" Content="1"
IsChecked="{Binding ItemMode, Converter={StaticResource IntToBoolConverter}, ConverterParameter=1}"/>
<RadioButton Name="_2" Grid.Column="2" Content="2"
IsChecked="{Binding ItemMode, Converter={StaticResource IntToBoolConverter}, ConverterParameter=2}"/>
<RadioButton Name="_3" Grid.Column="3" Content="3"
IsChecked="{Binding ItemMode, Converter={StaticResource IntToBoolConverter}, ConverterParameter=3}"/>
</Grid>
</Border>
</DataTemplate>
</Grid.Resources>
<Grid.DataContext>
<viewModels:ItemsList/>
</Grid.DataContext>
<ListBox ItemsSource="{Binding Items}"/>
</Grid>
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class IntToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null
&& parameter != null
&& value.ToString() == parameter.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return Binding.DoNothing;
int result;
if ((bool)value && int.TryParse(parameter.ToString(), out result))
{
return result;
}
return Binding.DoNothing;
}
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name= value;
RaisePropertyChanged(nameof(Name));
}
}
}
// можно сделать в базовом классе, в котором и реализовать интерфейс INotifyPropertyChanged
protected virtual void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private const byte VK_LMENU = 0xA4;
private const byte KEYEVENTF_EXTENDEDKEY = 0x01;
private const byte KEYEVENTF_KEYUP = 0x02;
private const byte KEYSCAN_LALT = 0xB8;
[DllImport("user32.dll")]
internal static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
public static void BringWindowToFront(IntPtr hwnd)
{
// симуляция нажатия клавиши ALT https://stackoverflow.com/a/13881647/1343405
keybd_event(VK_LMENU, KEYSCAN_LALT, 0, 0);
keybd_event(VK_LMENU, KEYSCAN_LALT, KEYEVENTF_KEYUP, 0);
SetForegroundWindow(hwnd);
}
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="Qwe"/>
<DataGridTextColumn Header="Rty"/>
<DataGridTextColumn Header="Uio"/>
</DataGrid.Columns>
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Width" Value="100"/>
</Style>
</DataGrid.Resources>
</DataGrid>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Width" Value="100"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
<Setter Property="Width" Value="100"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<ControlTemplate x:Key="{x:Static MenuItem.TopLevelHeaderTemplateKey}" TargetType="{x:Type MenuItem}">
<Border Name="Border" >
<Grid>
<ContentPresenter Margin="6,3,6,3" ContentSource="Header" RecognizesAccessKey="True" />
<Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsSubmenuOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Fade">
<Border Name="SubmenuBorder" SnapsToDevicePixels="True" Background="Transparent">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle" />
</Border>
</Popup>
</Grid>
</Border>
</ControlTemplate>
private ViewModel SelectModel(Model model) {}
). public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value)
{
return parameter != null ? Visibility.Collapsed : Visibility.Hidden;
}
return Visibility.Visible;
}
#region Свойства
public ObservableCollection<MyClass> Collection { get; set; } = new ObservableCollection<MyClass>
{
new MyClass { Name = "Иванов Иван" },
new MyClass { Name = "Петров Пётр" },
new MyClass { Name = "Сидоров Сидор" },
};
public MyClass SelectedCollection { get; set; };
#endregion
#region Команды
private ActionCommand _myCommand;
public ActionCommand MyCommand => _myCommand ?? (_myCommand = new ActionCommand(MyMethod));
private DelegateCommand<MyClass> _myDelegateCommand;
public DelegateCommand<MyClass> MyDelegateCommand => _myDelegateCommand ?? (_myDelegateCommand = new DelegateCommand<MyClass>(MyMethod2, item => item != null);
private void MyMethod()
{
// обработка команды
}
private void MyMethod2(MyClass item)
{
// обработка команды
}
#endregion
<ListBox ItemsSource="{Binding Collection}" SelectedItem="{Binding SelectedItem}"/>
<Button Command="{Binding MyCommand}" Content="Команда 1"/>
<Button Command="{Binding MyDelegateCommand}" CommandParameter="{Binding SelectedItem}" Content="Команда 2"/>
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<ListBox ItemsSource="{Binding Collection}" SelectedItem="{Binding SelectedItemc}" DisplayMemberPath="Name">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding MyDelegateCommand}" CommandParameter="{Binding SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
public class DelegateCommand<T> : ICommand
{
#region Private fields
private readonly Action<T> _execute;
private readonly Func<T, bool> _canExecute;
#endregion
#region Constructors
public DelegateCommand(Action<T> execute, Func<T, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region DelegateCommand
public void Execute(T parameter)
{
var handler = _execute;
if (handler != null)
{
handler(parameter);
}
}
public bool CanExecute(T parameter)
{
var handler = _canExecute;
return handler == null || handler(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
#region ICommand
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
#endregion
}
public class DelegateCommand : DelegateCommand<object>
{
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
: base(execute, canExecute)
{
}
}
public class ActionCommand : DelegateCommand<object>, ICommand
{
#region Private fields
private readonly Action _action;
private readonly Func<bool> _canExecute;
#endregion
#region Constructors
public ActionCommand(Action action, Func<bool> canExecute = null)
: base(null, null)
{
_action = action;
_canExecute = canExecute;
}
#endregion
#region ActionCommand
public void Execute()
{
var handler = _action;
if (handler != null)
{
handler();
}
}
public bool CanExecute()
{
var handler = _canExecute;
return handler == null || handler();
}
#endregion
#region ICommand
void ICommand.Execute(object parameter)
{
Execute();
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
#endregion
}