我有一个listview,它通过datatemplate显示行。当我选择一个项目时,我将所选项目添加到一个可观察的集合中,并将“CarIsSelected”的值设置为true,以便我知道哪个被选中。我在如何设置我选择的添加到observablecollection的项目的背景颜色方面遇到了麻烦?我希望这是有道理的。下面是我到目前为止的代码。再举一个例子,如果我选择“item1”,我将“item1”添加到集合中并突出显示“item1”的行。然后我选择“item2”,将“item2”添加到集合中,并突出显示“item2”的行。因此,应突出显示“item1”和“item2”。
xaml:
<ListView Name="lstExistingProblemList" HorizontalAlignment="Left" VerticalAlignment="Bottom"
ItemsSource="{Binding Path=ListOfCars}" SelectedItem="{Binding SelectedCar}"
SelectionMode="Single" Width="391" Grid.ColumnSpan="2">
<ListView.ItemTemplate>
<DataTemplate>
<Label Width="391" Margin="0,0,5,0" HorizontalAlignment="Left">
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}-{1}">
<Binding Path="Make" />
<Binding Path="Model" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
</Label>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
视图模型:
ObservableCollection<CarsInfo> selectedCarsLists = new ObservableCollection<CarsInfo>();
List<CarsInfo> listOfCars = new List<CarsInfo>();
CarsInfo selectedCar;
public List<CarsInfo> ListOfCars
{
get
{
listOfCars = DataSource.GetCarInfo();
return listOfCars;
}
}
public ObservableCollection<CarsInfo> SelectedCarsLists
{
get
{
return selectedCarsLists;
}
}
public CarsInfo SelectedCar
{
get
{
return selectedCar;
}
set
{
if (selectedCar != value)
{
selectedCar = value;
selectedCar.CarIsSelected = true;
selectedCarsLists.Add(selectedCar);
}
}
}
类:
public int Year { get; set; }
public string Description { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public bool CarIsSelected { get; set; }
答案 0 :(得分:0)
您可以为DataTrigger
属性设置CarIsSelected
,但您必须在INotifyPropertyChanged
课程中实施CarsInfo
以反映更改。
XAML:
<ListView.ItemTemplate>
<DataTemplate>
<Label x:Name="label" Width="391" Margin="0,0,5,0" HorizontalAlignment="Left">
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}-{1}">
<Binding Path="Make" />
<Binding Path="Model" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
</Label>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding CarIsSelected }" Value="True" >
<Setter TargetName="label" Property="Background" Value="Red" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
码
public class CarsInfo : INotifyPropertyChanged
{
public int Year { get; set; }
public string Description { get; set; }
public string Make { get; set; }
public string Model { get; set; }
private bool _carIsSelected;
public bool CarIsSelected
{
get { return _carIsSelected; }
set { _carIsSelected = value; NotifyPropertyChanged("CarIsSelected"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
结果: