【发布时间】:2013-01-03 11:30:06
【问题描述】:
我有一个列表视图,它通过数据模板显示行。当我选择一个项目时,我将所选项目添加到一个可观察的集合中,并将“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; }
【问题讨论】:
-
看看stackoverflow.com/questions/6171502/…Gishu 的回答。创建一个基于 IsSelected 切换的属性或函数以绑定为颜色。
-
你应该使用颜色转换器来改变所选项目的颜色
标签: c# wpf listview listviewitem