ListBoxのItemsPanelにCanvasを指定し、
Children1というObservableCollectionの中身を表示しています。
ボタン1が押下されたらChildren1を表示し、
ボタン2が押下されたらChildren2を表示するように、
動的にItemSourceを切り替えるにはどうすればよいでしょうか?
xaml
1<Window x:Class="WpfApp4.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:WpfApp4" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="450" Width="800"> 9 <StackPanel> 10 <Button>チルドレン1</Button> 11 <Button>チルドレン2</Button> 12 <ListBox ItemsSource="{Binding Path=Children1}"> 13 <ListBox.ItemsPanel> 14 <ItemsPanelTemplate> 15 <Canvas /> 16 </ItemsPanelTemplate> 17 </ListBox.ItemsPanel> 18 19 <ListBox.ItemContainerStyle> 20 <Style TargetType="{x:Type ListBoxItem}"> 21 <Setter Property="Canvas.Left" Value="{Binding Path=X}"/> 22 <Setter Property="Canvas.Top" Value="{Binding Path=Y}"/> 23 </Style> 24 </ListBox.ItemContainerStyle> 25 <ListBox.ItemTemplate> 26 <DataTemplate> 27 <Rectangle Width="{Binding Path=Width}" Height="{Binding Path=Height}" Fill="{Binding Path=Color}"/> 28 </DataTemplate> 29 </ListBox.ItemTemplate> 30 </ListBox> 31 </StackPanel> 32</Window>
C#
1 public partial class MainWindow : Window 2 { 3 public MainWindow() 4 { 5 InitializeComponent(); 6 var model = new Model(); 7 model.Children1.Add(new Item() { X = 50, Y = 100, Width = 50, Height = 50, Color = new SolidColorBrush(Colors.Red) }); 8 model.Children1.Add(new Item() { X = 200, Y = 150, Width = 10, Height = 10, Color = new SolidColorBrush(Colors.Green) }); 9 model.Children1.Add(new Item() { X = 100, Y = 300, Width = 50, Height = 20, Color = new SolidColorBrush(Colors.Blue) }); 10 11 // ボタン2が押されたらこちらを表示したい 12 model.Children2.Add(new Item() { X = 10, Y = 20, Width = 50, Height = 50, Color = new SolidColorBrush(Colors.Blue) }); 13 model.Children2.Add(new Item() { X = 200, Y = 120, Width = 10, Height = 10, Color = new SolidColorBrush(Colors.Blue) }); 14 model.Children2.Add(new Item() { X = 200, Y = 300, Width = 50, Height = 20, Color = new SolidColorBrush(Colors.Blue) }); 15 this.DataContext = model; 16 } 17 } 18 class Model 19 { 20 public ObservableCollection<Item> Children1 { get; private set; } 21 public ObservableCollection<Item> Children2 { get; private set; } 22 public Model() 23 { 24 Children1 = new ObservableCollection<Item>(); 25 // ボタン2が押されたらこちらを表示したい 26 Children2 = new ObservableCollection<Item>(); 27 } 28 } 29 30 class Item 31 { 32 public double X { get; set; } 33 public double Y { get; set; } 34 public double Width { get; set; } 35 public double Height { get; set; } 36 public SolidColorBrush Color { get; set; } 37 }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。