c# - WPF C# MVVM 用户控件绑定问题
问题描述
我为每个项目(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>
我有一个视图模型(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 项,但我猜我的数据绑定错误?我在看什么?
为清晰起见添加 ScreenViewItemControl
<UserControl.Resources>
<DataTemplate x:Key="ScreenViewItemTemplate">
<Border Padding="0 3"
Margin="20 20 0 0"
BorderThickness="2"
BorderBrush="{StaticResource BlueBrush}"
CornerRadius="20"
Height="210"
Width="192"
Background="{StaticResource BackgroundWhiteBrush}">
<StackPanel Orientation="Vertical" Margin="0 3">
<!-- Device Name -->
<TextBlock Width="192" Height="30"
TextAlignment="Center"
FontWeight="Bold"
FontSize="{StaticResource FontSizeXL}"
Text="{Binding Name}" />
<!-- ScreenShot -->
<Image Width="192" Height="108"
Margin="0 6"
Source="{Binding ScreenShot}" />
<StackPanel Orientation="Vertical" >
<!-- Device Status -->
<TextBlock Height="20"
Text="{Binding Status}"
TextAlignment="Center"
Padding="6 4" />
<!-- Device Location -->
<TextBlock Height="20"
Text="{Binding Location}"
TextAlignment="Center"
Padding="6 4" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</UserControl.Resources>
<ListBoxItem Style="{StaticResource ScreenViewStyle}"/>
解决方案
您应该ItemTemplate
为此定义ListBox
。默认情况下,如果将对象集合绑定到ListBox
它们的ToString()
方法,则会调用它们来表示此列表中的每个对象。
下面是一个如何做到这一点的示例(ListBox
为简洁起见,我删除了所有属性)。
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Status}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
正如罗伯特在评论中指出的那样,您还可以覆盖类ToString()
中的方法ScreenInfo
。但这取决于您想向用户显示什么。如果它是简单的文本,你可以使用覆盖的ToString()
方法,但如果你想用更花哨的方式显示你的项目,你应该使用ItemTemplate
. 你可以定义你的类中ItemTemplate
的每一个属性应该如何显示给用户。
推荐阅读
- java - Android Studio 导入新模块时项目不显示在项目结构中
- javascript - 将块作用域中的变量值用作全局作用域中的简单变量 - JAVASCRIPT。在火灾商店
- geometry - 几何找到从正方形的边缘到该正方形内最大可能圆的边缘的距离
- c - C 中的内存管理 - Linux 内核
- php - 在 php 中使用 for each 迭代 mysql 查询
- r - 将一个 sf 对象导出到多个 shapefile
- ios - 如何将自定义脚本传递给 ./configure 以在编译后运行?
- android - 如何从表 SQLite 中获取最后一条记录
- php - 更新了 composer.json 中的 symfony,但在尝试使用“require”安装新软件包时出现错误
- node.js - Axios - 请求失败,状态码 400 错误