我正在尝试学习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>
目前我的组合框正在拉开,因为ComboBox中的每个选项都是来自'System.Collections.Objectmodel.ObservableCollection`1 [SteamCodes.Codes]'
行的一封信。这些字母中的每个字母都是组合框中的不同下拉选项。
我出错的任何想法。
答案 0 :(得分:4)
您的ComboBox
ItemSource
必须是项目的集合,而不是字符串:
steamCode.ItemsSource = codes;
您还必须通过设置DisplayMemberPath
属性来指定商品的哪个属性必须被视为要在组合框中显示的值:
steamCode.DisplayMemberPath = "Code";
要指定绑定对象的哪个属性将用作实际选定值,您必须使用SelectedValuePath
属性:
steamCode.SelectedValuePath = "CodeID";
MVVM方法是:
public class ViewModel
{
public ObservableCollection<Codes> Codes { get; }
= new ObservableCollection<Codes>();
}
MainWindow构造函数:
public MainWindow()
{
InitializeComponent();
var viewModel = new ViewModel();
viewModel.Codes.Add(new Codes { CodeID = "1", Code = "CODETEXT" });
DataContext = viewModel;
}
XAML:
<ComboBox ItemsSource="{Binding Codes}" DisplayMemberPath="Code" .../>