ComboBox(Previous DataContext)在UWP中将SelectedItem属性设置为null值?

时间:2017-09-08 08:50:39

标签: c# combobox uwp

最初,ComboBox DataContext设置为Profession1SelectedValue为政治家。在运行时,我将Datacontext更改为Profession2。这样做会将Profession1更改为null。

请参考以下代码:

<Page.Resources>
    <local:MainPageViewModel x:Key="datacontent"></local:MainPageViewModel>
</Page.Resources>

<ComboBox x:Name="comboBox"
    ItemsSource="{Binding Professions,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
    SelectedItem="{Binding Profession, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
    Width="100"
    Height="100"                              
    VerticalAlignment="Center"
    HorizontalAlignment="Stretch" />

代码背后:

var datacontent = (this.Resources["datacontent"] as MainPageViewModel);
this.comboBox.DataContext = datacontent.Profession1;

型号:

public class MainPageViewModel
{       
    public MainPageViewModel()
    {
        Profession1 = new Person();        
        Profession2 = new Person();
    }
    private Person profession1;

    public Person Profession1
    {
        get { return profession1; }
        set { this.profession1 = value; }
    }

    private Person profession2;

    public Person Profession2
    {
        get { return profession2; }
        set { this.profession2 = value; }
    }
}

public class Person : INotifyPropertyChanged
{       
    public Person()
    {
        _professions = new List<string>();
        _professions.Add("Lawyer");
        _professions.Add("Politician");
        _professions.Add("Other");
    }

    private string _profession;
    public string Profession
    {
        get
        {
            if (string.IsNullOrWhiteSpace(_profession))
            {
                // _profession = _professions.LastOrDefault();
            }
            return _profession;
        }
        set
        {
            if (_profession != value)
            {
                _profession = value;
                NotifyPropertyChanged("Profession");
            }
        }
    }      

    private List<string> _professions;

    public List<string> Professions
    {
        get
        {
            return _professions;
        }
    }
}

我使用下面的代码来检查以前的datacontext(Profession1-&gt; Professon)值。

代码

((this.Resources["datacontent"] as MainPageViewModel).Profession1 as Person).Profession 

输出为:null。 预期价值:政治家

请有人建议。

1 个答案:

答案 0 :(得分:1)

  

((this.Resources["datacontent"] as MainPageViewModel).Profession1 as Person).Profession

     

输出为:null。期望值:政治家   请有人建议。

问题在于,当您修改combobox的DataContext时,DataContext首先设置为null,然后转为Profession2。因此Profession的{​​{1}}属性将设置为null。根据您的要求,您可以设置判断条件来解决此问题。

Profession1