這是我的 XAML:
<Window x:Class="WpfApp2.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:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<ComboBox x:Name="CB" ItemsSource="{Binding OC}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ItemName}"></TextBlock>
<TextBlock Text="{Binding FileName}"></TextBlock>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Click="Button_Click" Content="Try"></Button>
</StackPanel>
</Window>
這是代碼隱藏:
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 WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<ObjectItem> OC { get; set; } = new ObservableCollection<ObjectItem>();
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
OC.Add(new ObjectItem() { ItemName = "123", FileName = "abc.txt" });
OC.Add(new ObjectItem() { ItemName = "456", FileName = "cde.txt" });
OC.Add(new ObjectItem() { ItemName = "789", FileName = "efg.txt" });
}
public class ObjectItem {
public string ItemName { get; set; }
public string FileName { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CB.SelectedValue = new ObjectItem() { ItemName = "000", FileName = "ooo.txt" };
}
}
}
當我單擊按鈕時,我希望 ComboBox 顯示我設定的內容,而不向 ObservableCollection 添加任何專案,就像這樣:
但是,當我單擊按鈕時它不起作用。它出什么問題了?
uj5u.com熱心網友回復:
SelectedValue 根據定義是 ObservableCollection 中的 SelectedValue。您必須將其添加到集合中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/521350.html
標籤:wpf