I have a simple application that has an ObservableCollection<Item>
collection bound to UniformGrid
. If I use:
Items.Add(new Item
{
ID = i.ToString(),
Name = i.ToString(),
TestCommand = new RelayCommand<Item>((Item) => ChangeName(Item))
});
Then the RelayCommand
that is bound to the UI fires as expected but if I change the previous line to:
Application.Current.Dispatcher.BeginInvoke(
new Action(()=>
{
Items.Add(new Item
{
ID=i.ToString(),
Name=i.ToString(),
TestCommand=new RelayCommand<Item>((Item)=>ChangeName(Item))
});
}));
The UI does not invoke the RelayCommand
. Can you explain why?
Code:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Data();
}
}
public class Item:INotifyPropertyChanged
{
private string id;
public string ID
{
get
{
return this.id;
}
set
{
this.id = value;
RaisePropertyChanged("ID");
}
}
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.RaisePropertyChanged("Name");
}
}
public RelayCommand<Item> TestCommand { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string info)
{
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
public class Data
{
public ObservableCollection<Item> Items { get; set; }
public Data()
{
Items = new ObservableCollection<Item>();
CreateBoxes();
}
public void ChangeName(Item Item)
{
Items.Select(x=>x.ID== Item.ID);
Item.Name = "Changed";
}
public void CreateBoxes()
{
for (int i=0;i<4;i++)
{
//Application.Current.Dispatcher.BeginInvoke( new Action(()=>{ Items.Add(new Item {ID=i.ToString(),Name=i.ToString(),TestCommand=new RelayCommand<Item>((Item)=>ChangeName(Item)) });}));
Items.Add(new Item { ID = i.ToString(), Name = i.ToString(), TestCommand = new RelayCommand<Item>((Item) => ChangeName(Item)) });
}
}
}
}
Xaml code:
<Grid>
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="LightBlue">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" Content="ID:"/>
<Label Grid.Column="1" Grid.Row="0" Content="Name:"/>
<Label Grid.Column="0" Grid.Row="1" Content="{Binding ID}"/>
<Label Grid.Column="1" Grid.Row="1" Content="{Binding Name}"/>
<Button Grid.Row="2" Grid.ColumnSpan="2" Content="Test" Command="{Binding TestCommand}" CommandParameter="{Binding .}"/>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="2" Columns="2">
</UniformGrid>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
</Grid>