簡體   English   中英

WPF 組合框初始值被所選項目覆蓋

[英]WPF Combobox initial value being overridden by selected item

我有以下問題:

當我的視圖加載時,組合框選擇的值為空。

問題

這是我的觀點的代碼:

<UserControl.Resources>
    ...
    <CollectionViewSource x:Key="SpecialtiesSource" Source="{Binding Path=Specialties}" />
    ...
</UserControl.Resources>

...

<ComboBox Grid.Row="11" Grid.Column="2" Name="Specialty" Style="{StaticResource ComboBoxItem}"
          SelectedIndex="0"
          IsEditable="True"
          TextSearch.TextPath="Name"
          DisplayMemberPath="Name" 
          ItemsSource="{Binding Source={StaticResource SpecialtiesSource}}" 
          SelectedItem="{Binding SelectedSpecialty}"
          SelectedValuePath="Name">
</ComboBox>

這是我的視圖模型:

private List<Specialty> _specialties;
public List<Specialty> Specialties
{
    get
    {
        return _specialties;
    }

    set
    {
            _specialties = value;
            NotifyOfPropertyChange(() => Specialties);
        }
    }

    private Specialty _selectedSpecialty;
    public Specialty SelectedSpecialty
    {
        get
        {
            return _selectedSpecialty;
        }

        set
        {
            if (value == null)
            {
                return;
            }

            _selectedSpecialty = value;
            NotifyOfPropertyChange(() => SelectedSpecialty);
        }
    }

型號:

public class Specialty : IGeneric
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string TabColour { get; set; }
    public string TextColour { get; set; }
    public bool? ActiveFlag { get; set; }
}

public interface IGeneric
{
    string Name { get; set; }
}

當我調試代碼時,我可以看到我的 Specialties 對象返回了正確的結果,因為當我單擊下拉菜單時,我可以看到我期望的所有結果。

然而,在它加載這個對象之后,我可以立即看到我的 SelectedSpecialty 對象然后被命中,這是空的。 我猜這是因為加載 ItemsSource 和嘗試在索引位置 0 處設置 SelectedItem 的值之間存在一些潛在的交互?

關於如何找出 SelectedItem 被設置的原因以及如何正確停止/設置我的 SpecialtiesSource 的第一個項目的任何輸入或建議?

我也不是 100% 有信心正確使用 SelectedValuePath。

綁定的 SelectedItem 從 null 開始。 與 ItemsSource 相同。 如果您看到一個列表,則必須在問題中未顯示的某處初始化 Specialties,然后設置 SelectedSpecialty。

或者,如果它是在運行時加載的靜態列表,請在獲取專業中創建列表。 然后您可以在運行時將 SelectedSpecialty 初始化為 Specialties 項目之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM