我有一个WPF窗口,其DataContext设置为ViewModel对象,并且具有子控件数据绑定到该DataContext(ViewModel)对象的属性。这些数据绑定控件正确显示了ViewModel对象中的数据。但是,有一个包含TextBlock的StatusBar,应该在基础ViewModel对象的bound属性更改时进行更新-并且TextBlock没有更新。
问题是由于以下事实:绑定期间(或将其设置为DataContext时)没有将任何模型附加到ViewModel对象的PropertyChanged
事件,因此对数据更改的通知未路由到TextBlock控件。
缩写XAML是这样的:
Window x:Class="MarketFeedViewer.MainWindow"
xmlns:marketFeedViewer="clr-namespace:MarketFeedViewer"
mc:Ignorable="d"
Title="Market Data Viewer" Height="500" Width="300" >
<Window.DataContext>
<marketFeedViewer:MarketDataViewModel />
</Window.DataContext>
<Grid Margin="0,0,0,0">
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Top" Grid.Row="0" Grid.ColumnSpan="2" Margin="0,3,3,0">
<Label>Host</Label>
<TextBox x:Name="Host" VerticalContentAlignment="Center" MinWidth="100" Text="{Binding Host}" />
<Label Content="Port" />
<TextBox x:Name="Port" MinWidth="50" VerticalContentAlignment="Center" Text="{Binding Port}"/>
</WrapPanel>
<DataGrid x:Name="PricesGrid" HorizontalAlignment="Center" Margin="5,5,5,5" Grid.Row="1" Grid.ColumnSpan="2"
Grid.Column="0"
VerticalAlignment="Stretch"
ItemsSource="{Binding MarketData}"
MinHeight="200" MinWidth="200" VerticalScrollBarVisibility="Auto"/>
<StatusBar Grid.Row="3" Grid.ColumnSpan="2" Grid.Column="0">
<StatusBarItem HorizontalAlignment="Right">
<TextBlock Name="StatusText" Text="{Binding FeedStatus}" />
</StatusBarItem>
</StatusBar>
</Grid>
</Window>
ViewModel类实现INotifyPropertyChanged
,并且从后台线程更新状态栏的基础属性时,它会触发PropertyChange事件:
public class MarketDataViewModel : INotifyPropertyChanged
{
public ObservableCollection<WPFL1Data> MarketData { get; set; }
...
public string FeedStatus
{
get { return GetStatus(); }
}
...
...
private void ClientOnOnStateChange(object sender, MarketFeedConnectionState e)
{
if (App.IsInvokeRequired)
{
App.InvokeMethod(() => ClientOnOnStateChange(sender, e));
return;
}
...
// here is where Status Bar's TextBlock should be notified
// that value has changed.
OnPropertyChanged(FeedStatus);
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
// problem is here: handler == null
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
XAML配置缺少的代码是什么?
答案 0 :(得分:3)
您正在将FeedStatus
属性值而不是其名称传递给OnPropertyChanged
方法。它应该看起来像这样:
OnPropertyChanged("FeedStatus");
或更妙的是:
OnPropertyChanged(nameof(FeedStatus));