如何将ListViewItem的前景色绑定到模型的属性?
public class UserModel : BaseModel
{
public string UserName { get; private set; }
public int UserID { get; private set; }
public Brush Colour
{
get
{
return m_colour;
}
set
{
if (object.ReferenceEquals(m_colour, value))
return;
m_colour = value;
OnPropertyChanged("Colour");
}
}
private Brush m_colour = Brushes.Black;
public UserModel(int userID, string userName)
{
UserName = userName;
UserID = userID;
}
}
<ListView Name="lvClients" Grid.Column="0" Grid.Row="0" Margin="0,0,5,0" ItemsSource="{Binding Users, Mode=OneWay}" DisplayMemberPath="UserName" />
答案 0 :(得分:2)
如何找到您的颜色属性取决于您的完整结构:
<ListView Name="lvClients" Grid.Column="0" Grid.Row="0" Margin="0,0,5,0" ItemsSource="{Binding Users, Mode=OneWay}" DisplayMemberPath="UserName">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Color}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
或者您只是直接绑定到Foreground
的{{1}},这会导致项目具有相同的前景。
答案 1 :(得分:0)
您应该使用ItemTemplate
。例如
<Window.Resources>
<DataTemplate x:Key="myTemplate">
<StackPanel Background={Binding Colour}>
<TextBlock Text="{Binding Path=UserName}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Users}"
ItemTemplate="{StaticResource myTemplate}"/>
有关详情,请访问:http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplate.aspx