WPF C#MVVM用户控件绑定问题

问题描述 投票:0回答:1

我对每个项目都有一个用户控件(ScreenViewItemControl)(可以正常运行,不添加代码,但是如果需要,可以添加。)>

然后我有一个用户控件来列出所有项目用户控件(ScreenViewControl),例如:

    <ListBox ItemsSource="{Binding Screens}"
             SelectedItem="{Binding SelectedScreen}" 
             ItemContainerStyle="{StaticResource ScreenViewStyle}"
             ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
             BorderThickness="0" 
             Background="Transparent">

        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>

我有一个ViewModel(ScreenViewViewModel):

    public ObservableCollection<ScreenInfo> Screens { get; set; }

        public ScreenInfo SelectedScreen { get; set; }

        public ScreenViewViewModel()
        {
            Screens = new ObservableCollection<ScreenInfo>
            {
                new ScreenInfo
                {
                    Name = "ScreenSoft 1",
                    Status = "Online",
                    Location = "First Floor",
                    Resolution = "1920x1080",
                },
            };            

         }

并且我将控件放置在具有以下内容的页面中

<local:ScreenViewControl />

我可以看到它正在创建第1个项目,但是我猜我在错误地进行数据绑定?我忽略了什么?

enter image description here

我对每个项目都有一个用户控件(ScreenViewItemControl)(可以正常运行),不添加代码,但是可以根据需要添加代码。然后,我有一个usercontrol列出所有项目usercontrol(ScreenViewControl),例如:<...>] >>>

c# wpf mvvm binding user-controls
1个回答
0
投票

您应为此ItemTemplate定义ListBox。默认情况下,如果将对象集合绑定到ListBox,则会调用其ToString()方法来表示此列表中的每个对象。

下面是一个示例,您可以做到这一点(为简便起见,我从ListBox中删除了所有属性)。

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>                
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding Status}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
© www.soinside.com 2019 - 2024. All rights reserved.