我有一个基于ObservableCollection Categories
绑定到tbl_Category
的组合框类别,其中包含两个属性CategoryName
和CategoryDescription
。现在,我想将SelectedValue
的{{1}}添加到产品表属性ComboBox
在我的构造函数中:
Prod_Category
组合框xaml:
cb.DataContext = Categories;
this.DataContext = new tbl_Product();
在我的保存产品活动中:
<Combobox x:Name="cb" ItemSource="{Binding Categories}" DisplayMemberPath="CategoryName" SelectedValuePath="CategoryName" SelectedValue="{Binding Prod_Category,Mode=TwoWay}"/>
即使完成所有这些操作,我也会tbl_Product prod = (tbl_Product)this.DataContext;
DataOperations.AddProduct(prod);
到Prod_Category
。
答案 0 :(得分:2)
您应该使用SelectedItem而不是SelectedValue,请参阅this。
除了您愿意做的事情不是那么清楚之外,我已经尝试根据我的理解实施您所要求的内容
public partial class MainWindow : Window,INotifyPropertyChanged
{
private ObservableCollection<Category> _categories;
public ObservableCollection<Category> Categories
{
get
{
return _categories;
}
set
{
if (_categories == value)
{
return;
}
_categories = value;
OnPropertyChanged();
}
}
private Category _prod_Category ;
public Category Prod_Category
{
get
{
return _prod_Category;
}
set
{
if (_prod_Category == value)
{
return;
}
_prod_Category = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Categories=new ObservableCollection<Category>()
{
new Category()
{
CategoryName = "Name1",
CategoryDescription = "Desc1"
},new Category()
{
CategoryName = "Name2",
CategoryDescription = "Desc2"
}
};
}
public void SaveButton_Click(object sender, RoutedEventArgs routedEventArgs)
{
if (Prod_Category!=null)
{
//add it to whatever you want
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Category
{
public String CategoryName { get; set; }
public String CategoryDescription { get; set; }
}
和xaml
<StackPanel>
<ComboBox x:Name="cb" ItemsSource="{Binding Categories}" DisplayMemberPath="CategoryName" SelectedValuePath="CategoryName" SelectedItem="{Binding Prod_Category,Mode=TwoWay}"/>
<Button Content="Save" Click="SaveButton_Click"></Button>
</StackPanel>
如果其中一个绑定属性发生任何更改,您应该考虑实施INotifyPropertyChanged
接口来通知用户界面