组合框项目取自一个表,一个字段,在其上进行绑定。在数据库中保存另一个表中的选定项目后,我希望选定的项目是已保存的项目。但所选项目丢失。所以,我的问题是:我可以将组合框绑定到两个 DataContexts 还是另一个解决方案?
举一个更清楚的例子:组合框项是从数据源中获取的预定义值,并且必须保存所选值并在界面上显示。因此,据我所见,必须是与预定义值的绑定,以及与保存的值的绑定,以建立与所选项目的连接。
有什么建议吗?
组合框项目取自一个表,一个字段,在其上进行绑定。在数据库中保存另一个表中的选定项目后,我希望选定的项目是已保存的项目。但所选项目丢失。所以,我的问题是:我可以将组合框绑定到两个 DataContexts 还是另一个解决方案?
举一个更清楚的例子:组合框项是从数据源中获取的预定义值,并且必须保存所选值并在界面上显示。因此,据我所见,必须是与预定义值的绑定,以及与保存的值的绑定,以建立与所选项目的连接。
有什么建议吗?
Ioana,我似乎没有得到你的目标..
如果你接受这个 xaml:
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300">
<StackPanel>
<TextBox Text="{Binding Path=SelectedText, Mode=TwoWay}"
Width="200"/>
<ComboBox Width="200"
VerticalAlignment="Center"
HorizontalAlignment="Center"
SelectedItem="{Binding Path=SelectedText, Mode=TwoWay}"
ItemsSource="{Binding Path=Texts, Mode=OneWay}">
</ComboBox>
</StackPanel>
</Window>
这个代码隐藏:
public partial class Window1 : INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
this.Texts = new List<string>(new[] {"foo","bar"});
this.DataContext = this;
}
private ObservableCollection<string> texts;
public ObservableCollection<string> Texts
{
get
{
return texts;
}
set
{
texts = value;
if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("Texts"));
}
}
private string selectedText;
public string SelectedText
{
get
{
return selectedText;
}
set
{
selectedText = value;
if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("SelectedText"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
您确实有 Items 和 selectedValue 数据绑定。
注意INotifyPropertyChanged。
这是你想要达到的目标吗?