简体   繁体   中英

TextBox not display value after ComboBox onChange (WPF, C#, Binding)

I have UserControl contains ComboBox and TextBox:

 <ComboBox x:Name="cmbId" SelectionChanged="cmbId_SelectionChanged" />
 <TextBox x:Name="txb1" Visibility="Hidden" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />

I have loaded values to ComboBox:

  public MyDataView()
  {
            InitializeComponent();
            MyDBViewDataContext mydata = new MyDBViewDataContext();
            cmbId.ItemsSource = (from q in mydata.test_views
                                        select q.Id).ToList();
  }

When user select item on ComboBox, the TextBox should display value:

private void cmbId_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
            int myId = 0;
            Int32.TryParse(cmbId.Text, out myId);

            txb1.Visibility = Visibility.Visible;

            MyDBViewDataContext myDataList = new MyDBViewDataContext();
            var queryAll = (from q in myDataList.test_views
                        where q.Id.Equals(myId)
                        select q);
 }

But it's not working. Something is missing or what I did wrong?

If both Id and FirstName are properties of your entity class, you could set the ItemsSource property of the ComboBox to an IEnumerable<YourEntityType> and bind the Text property of the TextBox to the FirstName property of the SelectedItem of the ComboBox :

public MyDataView()
{
    InitializeComponent();
    MyDBViewDataContext mydata = new MyDBViewDataContext();
    cmbId.ItemsSource = (from q in mydata.test_views
                         select q).ToList();
}

<ComboBox x:Name="cmbId" DisplayMemberPath="Id"/>
<TextBox x:Name="txb1" Visibility="Hidden" Text="{Binding Path=SelectedItem.FirstName, UpdateSourceTrigger=PropertyChanged, ElementName=cmbId}" />

Then there is no need to handle the SelectionChanged event at all.

The other option would be to actually set the Text property of the TextBox in the event handler:

txb1.Text = var queryAll = (from q in myDataList.test_views
                    where q.Id.Equals(myId)
                    select q.FirstName).FirstOrDefault();

You have binded your textbox with a property, but I can't see in your code whether you are setting your property. Your textbox will display the selected name when you set your property to the selected item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM