Listview绑定不会更新视图

时间:2014-04-14 06:19:17

标签: c# wpf listview mvvm

我为ListView设置了此设置,并且我正在尝试使 Binding 在我的MVVM结构中工作。

这是xaml代码:

<Window.Resources>
    <CollectionViewSource
        x:Key="DeviceList"
        Source="{Binding Path=DiscoveredDevicesList}">

    </CollectionViewSource>
</Window.Resources>
    <ListView
    Grid.Row="1" 
    Width="500"
    HorizontalAlignment="Left"
    Margin="10"
    Grid.Column="1"
    DataContext="{StaticResource DeviceList}"
    ItemsSource="{Binding}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Device name" DisplayMemberBinding="{Binding Path=DeviceName}"/>
                <GridViewColumn Header="Rssi" DisplayMemberBinding="{Binding Path=Rssi}"/>
                <GridViewColumn Header="GPS Row" DisplayMemberBinding="{Binding Path=GpsSignal}"/>
            </GridView>
        </ListView.View>
    </ListView>

以下是实现绑定的代码

    //Constructor 
    public MainWindowViewModel()
    {
        DiscoveredDevicesList = new ObservableCollection<MyDeviceInfo>();
    }

    private ObservableCollection<MyDeviceInfo> _DiscoveredDevicesList;
    public ObservableCollection<MyDeviceInfo> DiscoveredDevicesList
    {
        get
        {
            return _DiscoveredDevicesList;
        }
        set
        {
            _DiscoveredDevicesList = value;
            OnPropertyChanged("DiscoveredDevicesList");
        }
    }

使用Add()Clear()更新视图就好了,如下所示:

        var client = new BluetoothClient();
        DiscoveredDevicesList.Clear();
        IEnumerable<MyDeviceInfo> csaDevices = null;
        csaDevices = await DiscoverCsaDevicesAsync(client);

        foreach (var csaDevice in csaDevices)
        {
            DiscoveredDevicesList.Add(csaDevice);
            DiscoveredDevicesList.First().GpsSignal = true;
        }

因此,我可以看到GpsSignal的值在我看来从最初的相反处更改为ture

但是,如果我在按钮的OnClick中添加以下相同的行,则不会执行相同操作,并且值保持false,因为我没有使用任何Add()Clear()而我只是依靠OnPropertyChanged来为我做这个伎俩。

            DiscoveredDevicesList.First().GpsSignal = true;

按钮点击和文本块信息等其他绑定工作正常,然后我认为它不应该是在舞台背面实现绑定的问题。

非常感谢您对此提出的建议。

1 个答案:

答案 0 :(得分:1)

如果您的MyDeviceInfo类实现了INotifyPropertyChanged并且您的属性GpsSignal引发了OnPropertyChanged(),那么当您的绑定正确时,您应该会看到所有更改。

然而,我会以这种方式更改您的代码:

从您的资源中删除CollectionViewSource并使用简单绑定

<Window.Resources>

</Window.Resources>
<ListView ItemsSource="{Binding DeviceList}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Device name" DisplayMemberBinding="{Binding Path=DeviceName}"/>
            <GridViewColumn Header="Rssi" DisplayMemberBinding="{Binding Path=Rssi}"/>
            <GridViewColumn Header="GPS Row" DisplayMemberBinding="{Binding Path=GpsSignal}"/>
        </GridView>
    </ListView.View>
</ListView>

将窗口的datacontext设置为codebehind或xaml中的MainWindowViewModel。 而不是使用OnClick,请使用ICommands(RelayCommand或DelegateCommand)

<Button Command="{Binding MyCommand4GpsSignalIsTrue}" />