【问题标题】:Trying to show a combobox element in a textbox in WPF of C# using selectedChanged尝试使用 selectedChanged 在 C# 的 WPF 中的文本框中显示组合框元素
【发布时间】:2020-04-27 19:39:30
【问题描述】:

方法如下:

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

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

【问题讨论】:

  • 是的,当您执行 SelectedItem.ToString() 时,它会将整个对象的字符串表示形式放入 text 属性中。您需要将所需的属性分配给文本字段,

标签: c# wpf combobox textbox


【解决方案1】:

您正在编写 WPF 应用程序,就像使用 Winform 一样。这确实可行,但有更好的方法来做到这一点。使用 MVVM(模型视图 ViewModel)。 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;
}

【讨论】:

  • 为答案添加更多说明,例如this link 和一些说明为什么使用 MVVM 方法比使用事件更好。
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多