【问题标题】:WPF bind the foreground colour of a listviewitem [closed]WPF绑定listviewitem的前景色[关闭]
【发布时间】:2011-06-09 13:47:38
【问题描述】:

如何将 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" />

【问题讨论】:

  • 以问题形式提出问题并发布您自己的答案是完全可以接受的。但请做对。实际提出问题,并实际回答。
  • 可能只是我,但我看到一个问题却没有答案...?

标签: c# wpf mvvm binding listviewitem


【解决方案1】:

您应该使用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

【讨论】:

    【解决方案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>
    

    或者您直接绑定到ListViewForeground,这将导致项目具有相同的前景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-30
      • 2013-09-10
      • 1970-01-01
      • 2010-09-26
      • 2011-03-08
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      相关资源
      最近更新 更多