我有簡單的ListView觸發器,我也使用mvvm light RelayCommand。 主要問題是爲什麼當功能ChangeShowingMode(ObservableCollection<Employee> items)
在控制檯中觸發時,它只顯示Firing: 0
。爲什麼它不顯示Firing: 1
,Firing: 5
,Firing: 11
,Firing: 99
。如何做到這一點?ListView與混合觸發器的奇怪行爲
的xmlns:ⅰ= 「http://schemas.microsoft.com/expression/2010/interactions」 的xmlns:EI = 「http://schemas.microsoft.com/expression/2010/interactivity」
<Grid>
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding IsChecked}" VerticalAlignment="Center">
<ei:Interaction.Triggers>
<ei:EventTrigger EventName="Checked">
<ei:InvokeCommandAction Command="{Binding DataContext.IsCheckedTrueCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Views:MainWindow}}}" CommandParameter="{Binding .}"/>
</ei:EventTrigger>
</ei:Interaction.Triggers>
</CheckBox>
<Label Grid.Column="1" Content="{Binding Name}" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
代碼如下所示:
namespace WpfApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ListViewModel();
}
}
public class Employee : ViewModelBase
{
private bool isChecked;
public bool IsChecked
{
get
{
return this.isChecked;
}
set
{
this.isChecked = value;
this.RaisePropertyChanged("IsChecked");
}
}
public string Name { get; set; }
}
public class ListViewModel : ViewModelBase
{
private ObservableCollection<Employee> items;
public ObservableCollection<Employee> Items
{
get
{
return this.items;
}
set
{
this.items = value;
this.RaisePropertyChanged("Items");
}
}
public ListViewModel()
{
Items = new ObservableCollection<Employee>();
LoadAsync();
}
public void LoadAsync()
{
Task t = null;
t = Task.Factory.StartNew(new Action(() =>
{
System.Threading.Thread.Sleep(5000);
ObservableCollection<Employee> temporaryItems = new ObservableCollection<Employee>();
for (int i = 0; i < 100; i++)
{
temporaryItems.Add(new Employee { IsChecked = false, Name = i.ToString() });
}
Items = temporaryItems;
}));
t.ContinueWith((key) => { ChangeShowingMode(Items); });
}
public void ChangeShowingMode(ObservableCollection<Employee> items)
{
Items[0].IsChecked = true;
Items[1].IsChecked = true;
Items[5].IsChecked = true;
Items[11].IsChecked = true;
Items[99].IsChecked = true;
}
public RelayCommand<Employee> IsCheckedTrueCommand
{
get
{
return new RelayCommand<Employee>((emp) => Command(emp));
}
}
public void Command(Employee emp)
{
Console.WriteLine("Firing: {0}", emp.Name);
}
}
}
假設'IsChecked'引發'INPC.PropertyChanged'事件我猜這是做些什麼你做你它從'任務'。你可以通過調用'PropertyChanged'事件來改變任何''的Employee.IsChecked'屬性 – dkozl
你錯了,因爲t.ContinueWith((key)=> {ChangeShowingMode(Items);} ); 在UI線程中引發。我認爲問題在於虛擬化或其他類似的問題。 – A191919
不,它不。直到你指定了適當的'TaskScheduler',例如'TaskScheduler.FromCurrentSynchronizationContext()' – dkozl