我有一个有两个组合框的视图。一个是用户选择路由管道类型名称的地方,另一个是应该有所选管道类型的可用直径列表。
每当用户选择管道类型时,另一个组合框应更新可用直径列表。
AvailableDiameters和RoutingPipeTypeName属性在Context类中是静态的,它实现了INotifyPropertyChanged接口。在xaml中,我在这些属性中设置了绑定,在代码后面还有DataContext。
问题是,在初始化视图时,直径列表只会更新一次。
在调试时,我可以看到当管道类型名称上的选择被更改时,属性支持字段的值会正确更新,仅在UI中可用直径列表未更新...
上下文类:
public class Context : INotifyPropertyChanged
{
public static Context This { get; set; } = new Context();
public static string RoutingPipeTypeName
{
get => _routingPipeTypeName;
set
{
if (_routingPipeTypeName != value)
{
_routingPipeTypeName = value;
This.OnPropertyChanged(nameof(RoutingPipeTypeName));
}
}
}
public static List<double> AvailableDiameters
{
get => _availableDiameters;
set
{
//check if new list's elements are not equal
if (!value.All(_availableDiameters.Contains))
{
_availableDiameters = value;
This.OnPropertyChanged(nameof(AvailableDiameters));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML:
<ComboBox Width="80" SelectedValue="{Binding Path=RoutingPipeTypeName, Mode=OneWayToSource}">
<ComboBoxItem Content="Example pipe type 1"></ComboBoxItem>
<ComboBoxItem Content="Example pipe type 2"></ComboBoxItem>
</ComboBox>
<ComboBox Width="80" SelectedValue="{Binding Path=RoutingDiameter, Mode=OneWayToSource}" ItemsSource="{Binding Path=AvailableDiameters, Mode=OneWay}">
</ComboBox>
代码背后:
public Context AppContext => Context.This;
public MyView()
{
InitializeComponent();
Instance = this;
DataContext = AppContext;
}
负责更新直径列表的客户端类:
public void InitializeUIContext()
{
Context.This.PropertyChanged += UIContextChanged;
if (Cache.CachedPipeTypes.Count > 0)
Context.RoutingPipeTypeName = Cache.CachedPipeTypes.First().Key;
}
private void UIContextChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Context.RoutingPipeTypeName))
{
Context.AvailableDiameters = Cache.CachedPipeTypes.First().Value.GetAvailableDiameters();
}
}
我希望每次在管道类型属性上更改选择时,这样的设置都会更新直径组合框。相反,它只在视图初始化时更新一次...为什么?
不要使用静态属性绑定到对象(您已正确传递给视图的DataContext
)。
声明没有static
修饰符的属性,并用This.OnPropertyChanged
替换OnPropertyChanged
:
public string RoutingPipeTypeName
{
get => _routingPipeTypeName;
set
{
if (_routingPipeTypeName != value)
{
_routingPipeTypeName = value;
OnPropertyChanged(nameof(RoutingPipeTypeName));
}
}
}
您还应该从Context类中删除static This
并简单地编写
public Context AppContext { get; } = new Context();