【问题标题】:How to set a ComboBox's SelectedItem through code如何通过代码设置 ComboBox Selected Item
【发布时间】:2013-03-17 05:17:42
【问题描述】:

在我的用户控件中,我定义了一个组合框,如下所示:

<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 仍然为空。

【问题讨论】:

    标签: c# wpf binding combobox


    【解决方案1】:

    您尚未将SelectedItem 绑定到StopEventVariable。使用以下语法:SelectedItem="{Binding StopEventVariable}"

    还要确保 StopEventVariable 是一个属性。

    【讨论】:

    • 是的,StopEventVariable 是一个属性。我在代码部分绑定了 DAtaContext。
    • @user2165899 显示更多 XAML。你的 Window 的 DataContext 是什么?
    【解决方案2】:

    SelectedItem 属性与来自XAML 本身的源属性(StopEventVariable) 绑定

    <ComboBox x:Name="stopEventCombobox" 
              ItemsSource="{Binding}" 
              DisplayMemberPath ="EventVariableComboxItem" 
              SelectedItem="{Binding StopEventVariable}"/>
    

    【讨论】:

      【解决方案3】:

      如果您的意思是从后面的代码绑定,那么您必须执行以下操作:

      Binding b1 = new Binding("StopEventVariable");
      b1.Source = pvVarList;
      stopEventCombobox.SetBinding(ComboBox.SelectedItemProperty, b1);
      

      然后您只需设置属性 StopEventVariable。 例如:

      pvVarList.StopEventVariable = someItemsCollection[0];

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多