加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如果itemsource中不存在值,则Combobox指定null

发布时间:2020-12-15 21:49:47 所属栏目:百科 来源:网络整理
导读:我有一个Datagrid,双击所选行后,将启动一个编辑屏幕. 在此编辑屏幕上,有组合框,其值绑定到网格中的选定行. 有时,组合框中没有分配给组合框的值,因此组合框中的显示为空,但该值不为空. 如果itemsource集合中不存在该值,如何更新所选项目的值为null. 在上面的
我有一个Datagrid,双击所选行后,将启动一个编辑屏幕.
在此编辑屏幕上,有组合框,其值绑定到网格中的选定行.
有时,组合框中没有分配给组合框的值,因此组合框中的显示为空,但该值不为空.
如果itemsource集合中不存在该值,如何更新所选项目的值为null.

在上面的场景中,自第二个屏幕绑定到第一个屏幕上的Selected项目时,City的SelectedValue为“洛杉矶”,显示为空.
但由于集合中不存在“洛杉矶”,因此SelectedValue应为null.

解决方法

解决方案是将组合框的ItemsSource设置为列表(例如:“DeviceNameList”),并将此组合框的SelectedItem设置为与列表中的元素类型(SelectedDeviceName)匹配的变量.

现在,当您加载编辑屏幕时,它会将列表绑定到组合框并显示您设置的变量.

您必须编写一些代码来检查所选项是否出现在列表中,如果不是,则可以将值设置为零.

例:

XAML代码:

<ComboBox ItemsSource="{Binding Path=DeviceNameList}" SelectedItem="{Binding Path=SelectedDeviceName}" />

用于设置selectedItem的代码:

/// <summary>
    /// Gets or sets SelectedDeviceName.
    /// </summary>
    public ObservableCollection<string> DeviceNameList
    {
         get
        {
           return mDeviceNameList;
        }

        set
        {
            mDeviceNameList = value;
        }
    }

    /// <summary>
    /// Gets or sets SelectedDeviceName.
    /// </summary>
    public string SelectedDeviceName
    {
        get
        {
            return mSelectedDeviceName;
        }

        set
        {
            mSelectedDeviceName = value;
            NotifyPropertyChanged("SelectedDeviceName");
        }
    }

    /// <summary>
    /// Event PropertyChanged
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
    /// Function NotifyPropertyChanged
    /// </summary>
    /// <param name="property">
    /// The property.
    /// </param>
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(property));
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读