我有一个模型CATEGORY
,其中我有两个属性NAME
n DESCRIPTION
。现在我的组合框使用NAME
作为项目。在组合框中选择NAME时,我希望我的文本框的文本属性包含该类别DESCRIPTION
的{{1}}。
我使用Linq进行数据库查询。
答案 0 :(得分:1)
您需要使用TextBox
ComboBox
将SelectedItem
文本值绑定到ComboBox
的{{1}},并在此处如何:
ElementName
我将此窗口 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>
设置为其后面的代码Behind:
DataContext
模特:
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));
}
}