如何通过代码
在我的用户控制设置组合框的的SelectedItem,我如下定义的组合框:如何通过代码
<GroupBox x:Name="stopEventGroup" Header="Test">
<ComboBox x:Name="stopEventCombobox"
ItemsSource="{Binding}"
DisplayMemberPath ="EventVariableComboxItem"
SelectedItem="StopEventVariable"/>
</GroupBox>
StopEventVariable是我对象(日志)的财产。在代码的一部分,我的SelectionChanged事件绑定到一个处理方法:
stopEventCombobox.SelectionChanged += stopEventCombobox_SelectionChanged;
而且内部处理程序,我把它分配给我的对象的属性。
private void stopEventCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedVar = (LogPublicVariableView)stopEventCombobox.SelectedItem;
if ((log != null) && (selectedVar != null))
{
log.StopEventVariable = selectedVar.ExposedVariable;
}
}
在此构造函数的构造函数中,我绑定组合框的父级的数据上下文:
stopEventGroup.DataContext = pvVarList;
到现在为止,一切都可以正常工作。现在我的问题是。在我的对象(日志)存储值后,下次显示此用户控制器时,我希望组合框自动显示此值,我尝试在用户控制器的构造函数中的以下代码中执行此操作,但无法工作:
stopEventCombobox.SelectedItem = log.StopEventVariable;
分配后,stopEventCombobox.SelectedItem仍为空。
您还没有绑定SelectedItem
到StopEventVariable
。使用以下语法:SelectedItem="{Binding StopEventVariable}"
。
另外确保StopEventVariable
是一个属性。
绑定SelectedItem
属性与源属性(StopEventVariable)
从XAML本身
<ComboBox x:Name="stopEventCombobox"
ItemsSource="{Binding}"
DisplayMemberPath ="EventVariableComboxItem"
SelectedItem="{Binding StopEventVariable}"/>
谢谢,我将它绑定在xaml部分,但仍然无法工作。 – user2165899 2013-03-27 07:51:07
如果你的意思是从代码绑定后面,这里是你必须做的:
Binding b1 = new Binding("StopEventVariable");
b1.Source = pvVarList;
stopEventCombobox.SetBinding(ComboBox.SelectedItemProperty, b1);
然后你只需要设置属性StopEventVariable。例如: :
pvVarList.StopEventVariable = someItemsCollection [0];
是的,StopEventVariable是一个属性。我在代码部分绑定了DAtaContext。 – user2165899 2013-03-27 07:46:34
@ user2165899显示更多XAML。什么是你的窗口的DataContext? – 2013-03-27 07:55:51