我有以下问题。
ListView中的背景颜色设置为LightGreen或White,无论boolflag是true还是false。
Window1.xaml:
<Window.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=BoolFlag}" Value="True">
<Setter Property="Background" Value="LightGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<ListView ItemsSource="{Binding Path=Personen}" SelectionMode="Single" SelectionChanged="ListViewSelectionChanged">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=Vorname}" Header="Vorname" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Nachname}" Header="Nachname" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Alter}" Header="Alter" />
<GridViewColumn DisplayMemberBinding="{Binding Path=BoolFlag}" Header="BoolFlag" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
Window1.xaml.cs:
public partial class Window1 : Window
{
private IList<Person> _personen = new List<Person>();
public Window1()
{
_personen.Add(new Person
{
Vorname = "Max",
Nachname = "Mustermann",
Alter = 18,
BoolFlag = false,
});
_personen.Add(new Person
{
Vorname = "Karl",
Nachname = "Mayer",
Alter = 27,
BoolFlag = true,
});
_personen.Add(new Person
{
Vorname = "Josef",
Nachname = "Huber",
Alter = 38,
BoolFlag = false,
});
DataContext = this;
InitializeComponent();
}
public IList<Person> Personen
{
get
{
return _personen;
}
}
private void ListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Person person = e.AddedItems[0] as Person;
if (person != null)
{
if (person.BoolFlag)
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.Green;
}
else
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.RoyalBlue;
}
}
}
}
Person.cs:
public class Person
{
public string Vorname { get; set; }
public string Nachname { get; set; }
public int Alter { get; set; }
public bool BoolFlag { get; set; }
}
现在我想根据boolflag设置所选项目的高亮颜色。 在Code-Behind中,我这样做:
private void ListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Person person = e.AddedItems[0] as Person;
if (person != null)
{
if (person.BoolFlag)
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.Green;
}
else
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.RoyalBlue;
}
}
}
}
这很好用,但现在我想在XAML文件中定义上面的代码。
使用
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Green" />
我可以覆盖默认值。但是,它可以工作,但所有选定项目的颜色都设置为绿色。我尝试过不同的方法在XAML中切换Green和Blue之间HighlightBrushKey的颜色,具体取决于boolflag,但我没有成功。
你可以帮助我并给我一些例子吗?
答案 0 :(得分:1)
不知道为什么highlightBrushKey不那么灵活。出于类似的原因,我开始使用其边框来设置所选项目背景颜色的另一种方法。您可以查看此http://vbcity.com/blogs/xtab/archive/2009/06/28/background-color-for-wpf-listbox-selected-item.aspx