试图在C#的WPF中使用selectedChanged在文本框中显示一个组合框元素。

问题描述 投票:0回答:1

下面是方法。

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

我在comboBox里放了一个列表 当我编译程序的时候,文本框会显示下一个: ComboBox_MicroDocu.MainWindow+Ciudades, 其中 "Ciudades "引用了我的类.

c# wpf combobox textbox
1个回答
0
投票

您正在编写WPF应用程序,就像您在Winform中做的那样。这应该是可行的,但是有一个更好的方法。使用MVVM(Model View ViewModel).MVVM是伟大的,因为它允许你从你的业务逻辑(viewModels)中解耦你的视图(xaml)。它对可测试性也很好.在这里查看一些好的资源。https:/www.tutorialspoint.commvvmindex.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;
}
© www.soinside.com 2019 - 2024. All rights reserved.