WPF数据绑定 - 未设置PropertyChanged处理程序

问题描述 投票:0回答:1

我有一个WPF窗口,其DataContext设置为ViewModel对象,并具有数据绑定到该DataContext(ViewModel)对象的属性的子控件。这些数据绑定控件正在显示ViewModel对象中的数据。但是,有一个包含TextBlock的StatusBar,当底层ViewModel对象的绑定属性发生更改时,它应该更新 - 并且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配置的缺失代码?

c# wpf data-binding
1个回答
3
投票

您将FeedStatus属性值传递给OnPropertyChanged方法,而不是其名称。它应该如下所示:

OnPropertyChanged("FeedStatus");

或更好的这个:

OnPropertyChanged(nameof(FeedStatus));
© www.soinside.com 2019 - 2024. All rights reserved.