如果我理解正确,您可以正常工作,以便当您选择列表中的项目时,会显示选定的模板银色背景,但是当您使用代码设置选定的项目时,它不会显示?
我创建了一个有效的简单示例,我必须进行的更改是将列表视图上的 selecteditem 属性的绑定设置为两种方式。
<ListView SelectedItem="{Binding MySelectedItem, Mode=TwoWay}">
我的示例使用 Caliburn Micro 但这并不重要。
这是我的示例代码,演示了它的工作原理......
查看型号:
public class ShellViewModel : Screen, IShell
{
private ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get
{
return this.people;
}
set
{
this.people = value;
this.NotifyOfPropertyChange(() => this.People);
}
}
private Person selectedPerson;
public Person SelectedPerson
{
get
{
return this.selectedPerson;
}
set
{
this.selectedPerson = value;
this.NotifyOfPropertyChange(() => this.SelectedPerson);
}
}
public ShellViewModel()
{
var russell = new Person { Name = "Russell" };
this.People.Add(new Person { Name = "Benjamin" });
this.People.Add(new Person { Name = "Steve" });
this.People.Add(russell);
this.SelectedPerson = russell;
}
View:
<Window x:Class="WpfApplication5.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Style x:Key="TextStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger
Binding="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsSelected}"
Value="True">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
<DataTemplate x:Key="MyItemTemplate">
<TextBlock Text="{Binding Name}" Style="{StaticResource TextStyle}"></TextBlock>
</DataTemplate>
</Window.Resources>
<Grid Background="White">
<ListView ItemsSource="{Binding People}" x:Name="People" ItemTemplate="{StaticResource MyItemTemplate}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
</ListView>
</Grid>
更改视图模型上的 SelectedPerson 属性也会显示在视图中。
希望这可以帮助!