如何从绑定源获取对象

时间:2017-05-31 07:30:12

标签: wpf object data-binding

在WPF中,我有一个绑定到数据集的列表框,如下所示:

<ListBox x:Name="lb_Configuration" SelectionMode="Extended" Height="100" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}">

SelectedItem有许多对象,例如: id name value ...

我怎样才能在后端代码中获得此值?我的想法是:

int myid;
myid = lb_Configuration.SelectedItem.<what method?>

或另外一种方法来达到我的目的?谢谢。

2 个答案:

答案 0 :(得分:0)

使用SelectedItem运算符,只需将Product属性转换为您的类型(as或您的类调用):

int myid;
var item = lb_Configuration.SelectedItem as Product;
if(item != null)
    myid = item.Id;

请注意,由于您将SelectedItem属性绑定到视图模型中的SelectedProduct属性,因此您可以直接在视图中访问Id的{​​{1}}属性虽然模型类:

SelectedProduct

答案 1 :(得分:-2)

如果要在后端代码中访问它,可以执行

myID = (lb_Configuration.SelectedItem as (Type of the object it is binded to)).ID;

但是避免使用xaml.cs代码是件好事。如果你解释一下你真正想要实现的目标,我可以用MVVM方式帮助你。

相关问题