我试图让项目的字体颜色在触发时发生变化,并且在我的生活中不能找出使单个项目发生变化的语法。我的代码:
C#:
public class Person
{
public string Name { get; set; }
public string Mode { get; set; }
public string Time { get; set; }
}
List<Person> personObjects = new List<Person>();
personObjects.Add(new Person()
{
Name = testVariable,
Mode = "Test",
Time = testString1,
});
PersonListView.ItemsSource = personObjects;
XAML:
<ListView x:Name="PersonListView"
HorizontalAlignment="Left"
Height="258"
Margin="5,268,0,0"
VerticalAlignment="Top"
Width="165"
FontSize="10"
ButtonBase.Click="GridViewColumnHeaderClickedHandler" >
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Height" Value="16" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Person"
Width="94"
DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Time"
Width="44"
DisplayMemberBinding="{Binding Time}"/>
</GridView>
</ListView.View>
</ListView>
我尝试使用ListViewItem
属性但没有运气
我试过了:
foreach (Person item in onCallListView.Items)
{
if(trigger)
{
item.Foreground = Brushes.Red;
}
}
我最接近的是在XAML中改变它:
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Foreground" Value="Red" />
</Style>
但它会更改列表中的所有项目,如何单独更改项目?
我有一个非常直接改变颜色的标签:
int secondsInMode = Convert.ToInt32(pullsDataFromString);
if (secondsInMode > 15 * 60)
{
personStatusLabel.Foreground = Brushes.Red;
}
我可以使用像:
这样的布尔值public bool RED = false;
if (secondsInMode > 15 * 60)
{
RED = true;
}
并使用布尔值触发DataTrigger?
答案 0 :(得分:2)
你可以这样触发:
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Height" Value="16" />
<DataTrigger Binding="{Binding Time}" Value="456">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style>
如果您的trigger
不仅仅是some_property == some_value
,那么您需要创建自己的ValueConverter
(请参阅下面的编辑)
如果您绑定的属性也可以动态更改,那么您还需要在您的媒体资源上实施PropertyChanged
- 请参阅http://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx
如果您需要更复杂的触发器,可以这样做:
C#:
public class TimeStringToIsLateConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Do the conversion from your Time (ie value) to your "should the text be red" bool
return ((string)value) == "456";
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Not needed!
return null;
}
}
XAML:
在顶部添加本地命名空间,例如:
<Window ...
xmlns:l="clr-namespace:WpfApplication4"
... />
然后有一些东西,例如:
<ListView ...>
<ListView.Resources>
<l:TimeStringToIsLateConverter x:Key="TimeColourConverter" />
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Height" Value="16" />
<Style.Triggers>
<DataTrigger Binding="{Binding Time, Converter={StaticResource TimeColourConverter}}" Value="True">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
...