尝试使用 selectedChanged 在 C# 的 WPF 文本框中显示组合框元素

Trying to show a combobox element in a textbox in WPF of C# using selectedChanged

方法如下:

private void Capitales_SelectedChanged(object sender, RoutedEventArgs e)
{
    string s = Capitales.SelectedItem.ToString();
    tb.Text = "Selection: " + s;
}

我在组合框中放置一个列表,当我编译程序时,文本框显示下一个:ComboBox_MicroDocu.MainWindow+Ciudades,其中 "Ciudades" 引用我的 class。

您正在像使用 Winform 一样编写 WPF 应用程序。这可以工作,但有更好的方法来做到这一点。使用 MVVM(模型视图视图模型)。 MVVM 很棒,因为它允许您将视图 (xaml) 与业务逻辑 (viewModels) 分离。它也非常适合可测试性。 在这里查看一些好的资源 https://www.tutorialspoint.com/mvvm/index.htm

您的代码应该是这样的:

MainWindow.xaml

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox Grid.Column="0" ItemsSource="{Binding Elements}" SelectedItem="{Binding SelectedElement}"/>
        <TextBox Grid.Column="1" Text="{Binding SelectedElement}"/>
    </Grid>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new ViewModel();
    }
}

ViewModel.cs

public class ViewModel : INotifyPropertyChanged
{
    private string _selectedElement;

    public IEnumerable<string> Elements
    {
        get
        {
            for(int i = 0; i < 10; i++)
            {
                yield return $"Element_{i}";
            }
        }
    }

    public string SelectedElement
    {
        get
        {
            return _selectedElement;
        }

        set
        {
            _selectedElement = value;
            RaisePropertyChanged();
        }
    }

    private void RaisePropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}