【发布时间】:2015-01-19 19:55:41
【问题描述】:
我有一个绑定到 ObservableList 的组合框(可观察列表继承自 ObservableCollection)。这是我的 Carrier 对象:
public class Carrier
{
/// <summary>
/// The carrier's name as it should be displayed to customers
/// </summary>
public string Name { get; set; }
/// <summary>
/// This is the domain that email-to-text messages should be sent to.
/// </summary>
public string TextBase { get; set; }
/// <summary>
/// Unique identifier for carriers
/// </summary>
public int CarrierId { get; set; }
}
我的问题是,在我的 ViewModel 中,我试图设置所选项目的值,但它没有在 UI 中设置。当我从组合框中选择一个选项时,它会正确修改我的视图模型(所以我知道绑定正在工作)。
这是我的 xaml:
<ComboBox ItemsSource="{Binding ElementName=UserInformationPage, Path=DataContext.PhoneCarriers}"
Style="{StaticResource ComboBox}"
Width="250"
DisplayMemberPath="Name"
SelectedItem="{Binding Path=SelectedCarrier, Mode=TwoWay}"
SelectedValuePath="CarrierId"
/>
这是我的视图模型:
public Carrier SelectedCarrier
{
get { return _selectedCarrier != null ? PhoneCarriers.First(c => c.CarrierId == _selectedCarrier.CarrierId) : PhoneCarriers.First(); }
set
{
if (_selectedCarrier == null || _selectedCarrier.CarrierId != value.CarrierId)
{
Set(ref _selectedCarrier, value);
if (User != null)
User.Phone.Carrier = value;
}
}
}
public UserDemographicsViewModel()
{
MessengerInstance.Register<SelectedUser>(this, m =>
{
User = m.User;
CheckCanShowPassword();
CheckCanResetPassword();
});
NavigationService.Navigated += (s, e) =>
{
if (e.Parameter is User)
{
User = e.Parameter as User;
if (User.Phone != null)
{
SelectedCarrier = User.Phone.Carrier;
}
}
};
IsPasswordTextShown = false;
TogglePasswordCommand = new RelayCommand(() => IsPasswordTextShown = !IsPasswordTextShown); //flip the state of password shown
SaveUserCommand = new RelayCommand<User>(SaveUser, u => CanSaveUser());
ResetPasswordCommand = new RelayCommand(TryResetPassword, () => User != null && User.UserId != 0); //we have a user and its not a new user
var repo = IoCContainer.GetContainer().Resolve<IAccountRepository>();
var loggedInUser = App.Session.Get<User>("AuthenticatedUser");
PhoneCarriers = new ObservableList<Carrier>(repo.GetPhoneCarriers(loggedInUser.AccountId));
}
正如我所说,我知道我已正确绑定到 SelectedCarrier 属性,但由于某种原因,当 SelectedCarrier 与 PhoneCarriers 集合中的值匹配时,下拉列表中的值显示为空白。
更新
我尝试使用以下内容简化我的 SelectedCarrier 属性:
public Carrier SelectedCarrier
{
get { return _selectedCarrier; }
set
{
if (_selectedCarrier == null || _selectedCarrier.CarrierId != value.CarrierId)
{
_selectedCarrier = value;
RaisePropertyChanged("SelectedCarrier");
if (User != null)
User.Phone.Carrier = value;
}
}
}
我知道我有一个选定的运营商,因为在调试时,如果我更改下拉值,我可以在 _selectedCarrier 更改为新值之前看到它的值(并且它很好地击中断点)。该值只是不显示在用户界面中。
【问题讨论】:
-
同时设置
ItemsSource和SelectedItem在 XAML 中是一个出了名的问题。顺序需要正确,您设置的其他属性可能也会对其产生影响。
标签: c# xaml combobox windows-runtime