我将我的组合框绑定到列表中,SelectedItem
也绑定到代码后面的CurrentCode
属性。现在每件事都显示得很好,所选项目按预期设置。但是,让我通过点击按钮更改CurrentCode
的值。为什么组合框没有更新?
<ComboBox ItemsSource="{Binding Path=Codes}"
SelectedItem="{Binding CurrentCode,
RelativeSource={RelativeSource FindAncestor, AncestorType=Window},
Mode=OneTime}"/>
public partial class SettingsWindow
{
public List<string> Codes { get; set; }
public string CurrentCode
{
get
{
return Building.Code;
}
}
public SettingsWindow()
{
InitializeComponent();
Codes = new List<string> {"ACI Code", "BS Code"};
DataContext = this;
}
private void OK_OnClick(object sender, RoutedEventArgs e)
{
Building.Code = "BS Code;
}
}
答案 0 :(得分:1)
更改属性支持字段时应该实现INotifyPropertyChanged并引发PropertyChanged事件 http://msdn.microsoft.com/en-us/library/ms743695%28v=vs.110%29.aspx
答案 1 :(得分:1)
如果你在代码隐藏中,你可以给ComboBox一个名字并直接访问它。
如果你想让它与属性一起工作(理想情况下将它移动到它自己的类中,以MVVM方式,并将你的Window的DataContext设置为&#34;查看模型&#34;类),你&# 39; ll需要实现INotifyPropertyChanged
:
public partial class SettingsWindow : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private void OK_OnClick(object sender, RoutedEventArgs e)
{
Building.Code = "BS Code;
OnPropertyChanged("CurrentCode");
}
...
}