【发布时间】:2016-09-28 20:50:42
【问题描述】:
我正在尝试学习 WPF 以及最重要的 MVVM 做事风格。
我有一个简单的练习应用程序,我想在组合框中显示代码。
我的代码
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SteamCodes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<Codes> codes;
public MainWindow()
{
InitializeComponent();
codes = new ObservableCollection<Codes>()
{
new Codes() {CodeID = "1", Code="CODETEXT"}
};
steamCode.ItemsSource = codes.ToString();
}
}
public class Codes
{
public string CodeID { get; set; }
public string Code { get; set; }
}
}
我的 XAML
<Window x:Class="SteamCodes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SteamCodes"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="steamCode" ItemsSource="{Binding Source = Codes}" HorizontalAlignment="Left" Height="43" Margin="122,37,0,0" VerticalAlignment="Top" Width="259"/>
</Grid>
</Window>
目前我的 Combo 框正在通过,因为 ComboBox 中的每个选项都是来自“System.Collections.Objectmodel.ObservableCollection`1[SteamCodes.Codes]”行中的一个字母
这些字母中的每一个都是组合框中的不同下拉选项。
我出错的任何想法。
【问题讨论】:
-
ItemsSource应该绑定到数据项的集合。您正在分配(不绑定)一个字符串,它是字符的集合。 XAML 中的绑定表达式不起作用。在此处阅读基础知识:Data Binding Overview。 -
好的,谢谢,我现在看看那个链接。
-
它还应该做什么?你正在把你的整个收藏放在一个字符串中。您必须编码的图像,如果项目的源设置为两个值,组合框应如何决定显示哪个 -> CodeID 和 Code