Skip to main content
 首页 » 编程设计

c#之WPF之将带有字符串列表的类绑定(bind)到 ListBox

2024年02月06日22cyq1162

我在将多个列表绑定(bind)到一个列表框时遇到问题。我希望每个 List 都有一个不同颜色的不同 DataTemplate。

我有以下模型类

public class Users 
{ 
        public Members Members{ get; set; } 
} 
 
public class Members 
{ 
        public List<string> Moderators { get; set; } 
        public List<string> Viewers { get; set; } 
} 

我使用 INotifyPropertyChanged 跟随 ViewModel

private Users users; 
 
public Users Users 
{ 
    get { return users; } 
    set 
    { 
        users= value; 
        RaisePropertyChanged("Users"); 
    } 
} 

我绑定(bind)到这个 ListBox

<ListBox ItemsSource="{Binding Users.Members.Viewers}"> 
        <ListBox.ItemTemplate> 
            <DataTemplate> 
                <StackPanel Orientation="Horizontal"> 
                    <TextBlock Text="{Binding}" /> 
                </StackPanel> 
            </DataTemplate> 
        </ListBox.ItemTemplate> 
 </ListBox> 

现在我只有一个列表绑定(bind)到列表框。它工作得很好,但我希望其他列表也绑定(bind)到同一个列表框。除此之外,我希望版主有一个不同的模板。

我尝试了很多不同的方法,但似乎没有任何效果。

请您参考如下方法:

与其从原始对象中删除名称,不如保留它并根据原始类指定不同的颜色?

Besides that I want that Moderators have a different template.

如果你只有字符串那是不可能的。请记住,列表框最终只能看到一个列表;所以在一个列表中,如何标记一个字符串作为版主或查看者?

a different DataTemplate with a different color.

如果只有字符串,我建议您创建包装类,一个用于版主,一个用于观众,然后将字符串投影到要保存的那些类中。然后你可以按照我下面的建议/例子。


通过使用 Composite 集合来保存不同的项目(或者实际上可以使用基类列表或接口(interface)列表,如果实例具有这种共性),然后有专门的数据模板看起来对于原始类(class),这是可以做到的。

例子

我有两个类,一个名为 Ships,另一个名为 Passage。请注意,这两个类都有一个 Name 属性,但是可以在模板中为其中一个或两个使用 Name 以外的属性。

下面我定义了数据模板和我的列表框。

<Grid> 
    <Grid.Resources> 
        <DataTemplate DataType="{x:Type c:Ship}"> 
            <TextBlock Text="{Binding Path=Name}" 
                        Foreground="Red" /> 
        </DataTemplate> 
        <DataTemplate DataType="{x:Type c:Passage}"> 
            <TextBlock Text="{Binding Path=Name}" 
                        Foreground="Blue" /> 
        </DataTemplate> 
    </Grid.Resources> 
    <ListBox Name="myListBox" 
                Height="300" 
                Width="200" 
                ItemsSource="{Binding MyCompositeCollection}"> 
    </ListBox> 
</Grid> 

所以会发生什么,我的船将是红色的, channel 将是蓝色的。


这是我在虚拟机中的代码:

private CompositeCollection _MyCompositeCollection; 
 
public CompositeCollection MyCompositeCollection 
{ 
    get { return _MyCompositeCollection; } 
    set { _MyCompositeCollection = value; OnPropertyChanged("MyCompositeCollection"); } 
} 

这里我加载复合集合:

var temp  = new CompositeCollection(); 
 
Ships.ForEach(sh => temp.Add(sh)); 
Passages.ForEach(ps => temp.Add(ps)); 
 
MyCompositeCollection = temp;