我用INotifyPropertyChanged 创建了一个名为Data 的类。
public class Data : INotifyPropertyChanged
{
public string Text { get; set; }
private string selectedBackGround;
public string SelectedBackGround
{
get
{
return selectedBackGround;
}
set
{
selectedBackGround = value;
NotifyPropertyChanged("SelectedBackGround");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在 Xaml 中,我重写了 ControlTemplate 并使用 SelectedBackGround 属性绑定到 StackPanel 背景。 SelectedBackGround 属性仅用于通过代码更改颜色。
<ListView x:Name="ListView1" SelectionChanged="ListView_SelectionChanged" HorizontalAlignment="Left" Height="135.924" Margin="194.529,104.462,0,0" VerticalAlignment="Top" Width="302.311" ItemsSource="{Binding ListOfstring}" >
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal" Background="{Binding SelectedBackGround}">
<TextBlock Text="{Binding Text,UpdateSourceTrigger=Explicit}" Foreground="Black"/>
<Button x:Name="btn1" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Btn1_Click_1" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</ListView.ItemContainerStyle>
</ListView >
这就是我填写我的收藏的方式。
public MainWindow()
{
ListOfstring = new ObservableCollection<Data>();
InitializeComponent();
ListOfstring.Add( new Data{ Text="TEST1", SelectedBackGround = "White" });
ListOfstring.Add( new Data{ Text="TEST2", SelectedBackGround = "White" });
ListOfstring.Add( new Data{ Text="TEST3", SelectedBackGround = "White" });
ListOfstring.Add( new Data{ Text = "TEST4", SelectedBackGround = "White" });
this.DataContext = this;
}
如您所见,Button 是通过点击事件订阅的。
private void Btn1_Click_1(object sender, RoutedEventArgs e)
{
// Whenever you click on the any list item button, you are changing background
// of the 3rd item in the list view to Aqua Color.
ListOfstring[2].SelectedBackGround = "Aqua";
}