我正在研究 WPF 并且遇到了严重的问题。我有一个包含两列 ContactName 和 ContactTitle 的数据集。我已成功将所有数据加载到 ComboBox 中,甚至按 ContactName 对其进行排序。但是,我现在正尝试访问该数据并在 TextBox 中显示其中的一部分。(这当然只是一个概念验证类型的练习,最终产品将使用所选人员信息填充各种文本框)。问题是,我无法获取要填充到 TextBox 中的信息。这是我拥有的代码:
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace MultiBindingInWPF_CS
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
//Create DataSet
CustomersDataSet customerDataSet = new CustomersDataSet();
//Create DataTableAdapter
CustomersDataSetTableAdapters.CustomersTableAdapter taCustomers = new CustomersDataSetTableAdapters.CustomersTableAdapter();
taCustomers.Fill(customerDataSet.Customers);
//Sort Data
SortDescription sd = new SortDescription("ContactName", ListSortDirection.Descending);
//Designate ItemSource
this.ComboBox1.ItemsSource = customerDataSet.Customers;
//Apply Sort
this.ComboBox1.Items.SortDescriptions.Add(sd);
}
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
//Using SelectedIndex only to prove connection to TextBox is working
textBox1.Text = ComboBox1.SelectedIndex.ToString();
}
catch
{
textBox1.Text = "Invalid";
}
}
}
}
然后这是我的 XAML:
<Window x:Class="MultiBindingInWPF_CS.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
Title="Multibinding in WPF" Height="163" Width="300">
<Grid Loaded="Grid_Loaded">
<StackPanel Name="StackPanel1" Margin="12">
<Label Height="28" Name="Label1">List of Customers (Name AND Title :-) )</Label>
<ComboBox Height="23" Name="ComboBox1" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" IsTextSearchEnabled="True" SelectionChanged="ComboBox1_SelectionChanged" SelectedValue="{Binding Path=CustomerID}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock DataContext="{Binding}">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} - {1}">
<Binding Path="ContactName" />
<Binding Path="ContactTitle" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Height="23" Name="textBox1" Width="120"/>
</StackPanel>
</Grid>
</Window>
我的最终目标是通过获取所选值来动态填充 TextBox,并获取与该 CustomerID 关联的数据集中的信息,但仅将 SelectedItem 的文本填充到 TextBox 中将是一大步。
任何帮助是极大的赞赏。谢谢大家。