Wpf - 如何根据组合框选择获取文本框值

Wpf - how to get textbox value based on combobox selection

我有一个模型 CATEGORY,其中有两个属性 NAME n DESCRIPTION。现在我的组合框使用 NAME 作为项目。在组合框中选择名称时,我希望文本框的文本 属性 具有该类别 NAME.

DESCRIPTION

我正在使用 Linq 进行数据库查询。

您需要使用 ComboBox ElementNameTextBox 文本值绑定到 ComboBoxSelectedItem,这里是如何:

        Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}" Loaded="MainWindow_OnLoaded">
<StackPanel>
    <TextBox Text="{Binding Path=SelectedItem.Description, ElementName=CatComboBox}"/>
    <ComboBox ItemsSource="{Binding ListCategories}" x:Name="CatComboBox" DisplayMemberPath="Name"></ComboBox>        
</StackPanel>

我正在将此 window DataContext 设置为其代码 Behind 如下所示:

 public partial class MainWindow : Window,INotifyPropertyChanged 
{

    private ObservableCollection<Category> _listCategories;    
    public ObservableCollection<Category> ListCategories
    {
        get
        {
            return _listCategories;
        }

        set
        {
            if (_listCategories == value)
            {
                return;
            }

            _listCategories = value;
            OnPropertyChanged();
        }
    }
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        //Get the data from the DB
        ListCategories=new ObservableCollection<Category>()
        {
            new Category()
            {
                Name = "Name1",
                Description = "Descrition1"
            },
            new Category()
            {
                Name = "Name2",
                Description = "Descrition2"
            }
        };
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

模特:

public class Category
{
    public String Name { get; set; }
    public String Description { get; set; }
}