我有一个简单的应用程序,其ObservableCollection<Item>
集合绑定到UniformGrid
。如果我使用:使用BeginInvoke设置RelayCommand时未触发
Items.Add(new Item
{
ID = i.ToString(),
Name = i.ToString(),
TestCommand = new RelayCommand<Item>((Item) => ChangeName(Item))
});
然后绑定到UI火灾预期,但如果我前行更改为RelayCommand
:
Application.Current.Dispatcher.BeginInvoke(
new Action(()=>
{
Items.Add(new Item
{
ID=i.ToString(),
Name=i.ToString(),
TestCommand=new RelayCommand<Item>((Item)=>ChangeName(Item))
});
}));
的UI不会调用RelayCommand
。你能解释为什么吗?
代码:
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代码:
<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>