ItemsControl へのデータのバインドに関する 1 つの問題に直面しています。コード ビハインドからソースに項目を追加しますが、ItemsControl には反映されません。以下のコード サンプルのどこが間違っているかを修正してください。
<UserControl x:Class="DragDropListbox.SilverlightControl1"
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"
mc:Ignorable="d">
<UserControl.Resources>
<DataTemplate x:Name="MyDT">
<Grid DataContext="{Binding Mode=OneWay}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name,Mode=OneWay}"></TextBlock>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Grid.Column="0" Grid.Row="0">
<Button Content="Add" Height="23" x:Name="btnadd" Width="75" Margin="10,0" Click="btnadd_Click" />
<Button Content="Delete" Height="23" x:Name="btndelete" Width="75" Click="btndelete_Click" />
</StackPanel>
<StackPanel x:Name="stk" Orientation="Vertical" Grid.Row="1">
<ItemsControl x:Name="ic1"
ItemsSource="{Binding Path=AllEmp,Mode=OneWay}"
ItemTemplate="{StaticResource MyDT}">
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
Csファイルコード
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace DragDropListbox
{
public partial class SilverlightControl1 : UserControl
{
public SilverlightControl1()
{
InitializeComponent();
stk.DataContext = new Emps() { AllEmp = new List<emp>() { new emp() { Name = "Name - 0" } } };
}
private void btnadd_Click(object sender, RoutedEventArgs e)
{
var k = stk.DataContext as Emps;
k.AllEmp.Add(new emp() { Name = string.Format("Name - {0}", k.AllEmp.Count) });
}
private void btndelete_Click(object sender, RoutedEventArgs e)
{
var k = stk.DataContext as Emps;
if (k.AllEmp.Count > 0)
{
k.AllEmp.Remove(k.AllEmp[0]);
}
}
}
public class Emps : System.ComponentModel.INotifyPropertyChanged
{
private List<emp> _AllEmp;
public List<emp> AllEmp
{
get { return _AllEmp; }
set
{
_AllEmp = value;
OnPropertyChanged("AllEmp");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string property)
{
System.ComponentModel.PropertyChangedEventHandler ph = this.PropertyChanged;
if (ph != null)
{
ph(this, new System.ComponentModel.PropertyChangedEventArgs(property));
}
}
}
public class emp
{
public string Name { get; set; }
}
}