c# - 如果 itemsource 中不存在值,则 Combobox 分配 null

标签 c# wpf data-binding combobox mvvm-light

我有一个数据网格,双击选定的行后,将启动一个编辑屏幕。 在此编辑屏幕上,有组合框,其值绑定(bind)到网格中的选定行。 有时combobox赋值的值在combobox itemSource中不存在,所以combobox上显示为空,但value不为null。 如果 itemsource 集合中不存在该值,我如何更新所选项目的值,使其为 null。

在上述场景中,由于第二个屏幕绑定(bind)到第一个屏幕上的 Selected 项目,因此 City 的 SelectedValue 为“Los Angeles”并且 Display 为 Empty。 但是由于集合中不存在“洛杉矶”,因此 SelectedValue 应该为空。

最佳答案

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

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

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

示例:

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));
        }
    }

关于c# - 如果 itemsource 中不存在值,则 Combobox 分配 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16147582/

相关文章:

c# - DataGrid过滤,多输入,MVVM,C#

c# - 如果您没有任何异步代码,您如何处理返回 Task 的第 3 方接口(interface)?

c# - 过度使用 DataTable 不好吗?

.net - 样式 TargetType 属性问题

javascript - Knockoutjs 和 FancyForms : visible-binding not working on selectboxes using transformSelect

xaml - .NET MAUI 中的分组 CollectionView

c# - listbox isSelected DataTemplate 中的数据绑定(bind)

c# - 创建配置或 INI 文件以存储用户设置首选项

c# - NUnit 设置属性是否有代码味道?

c# - 转换器应该抛出任何类型的异常吗?