Skip to content

Instantly share code, notes, and snippets.

@runceel
Created May 15, 2012 14:10
Show Gist options
  • Save runceel/2702061 to your computer and use it in GitHub Desktop.
Save runceel/2702061 to your computer and use it in GitHub Desktop.
コードビハインド
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Text}" />
<Button Content="Del" Command="{Binding HelloCommand}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Microsoft.Practices.Prism.Commands;
namespace WpfApplication2
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel
{
Items = new ObservableCollection<ListItem>(
Enumerable.Range(1, 10).Select(i => new ListItem { Text = "Hello world" + i }))
};
}
}
public class MainWindowViewModel
{
public ObservableCollection<ListItem> Items { get; set; }
}
public class ListItem
{
public string Text { get; set; }
public DelegateCommand HelloCommand { get; private set; }
public ListItem()
{
this.HelloCommand = new DelegateCommand(() =>
{
MessageBox.Show("きた");
});
}
}
}
ここまでできたら、後はListItemのCommandの処理内で要素を消せればいいってことになるからやりようはいくらでもある。例えばListItemにMainWindowViewModelの参照を持たせておいて削除するとか、ListItemからMainWindowViewModelに対して削除要求を表すイベントを発行するとかetc...。
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Microsoft.Practices.Prism.Commands;
namespace WpfApplication2
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var mainWindowViewModel = new MainWindowViewModel();
mainWindowViewModel.Items = new ObservableCollection<ListItem>(
Enumerable.Range(1, 10).Select(i => new ListItem(mainWindowViewModel)
{
Text = "Hello world " + i
}));
this.DataContext = mainWindowViewModel;
}
}
public class MainWindowViewModel
{
public ObservableCollection<ListItem> Items { get; set; }
}
public class ListItem
{
private MainWindowViewModel parent;
public ListItem(MainWindowViewModel parent)
{
this.parent = parent;
this.HelloCommand = new DelegateCommand(() =>
{
this.parent.Items.Remove(this);
this.parent = null;
});
}
public string Text { get; set; }
public DelegateCommand HelloCommand { get; private set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment