在WPF中绑定ComboBox的问题

时间:2017-02-14 13:04:02

标签: wpf mvvm prism

以下是代码

<ComboBox Name="cmbRegisteredDriveList"
          Width="150" HorizontalAlignment="Center"
          ItemsSource="{Binding Path=DriveList}"
          SelectedItem="{Binding Path=SelectedDrive, Mode=TwoWay}"
          IsEnabled="{Binding IsBusy, Converter={StaticResource NotConverter}}"
          ItemContainerStyle="{StaticResource xxxx.ComboBoxItem.Style}">

    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock x:Name="tbTemplate" Width="250" Visibility="Collapsed"/>
                <TextBlock TextWrapping="NoWrap"
                           Text="{Binding VolumeLabel, Converter={StaticResource CenterEllipsisConverter}, ConverterParameter={x:Reference tbTemplate}}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

当我们更改驱动器的卷标时,我们会收到通知。但组合框中的选定项目不会刷新。谁可以帮我这个事。我想在组合框中显示所选项目的已更改卷标。

public ObservableCollection<DiskDrive> _driveList;
public ObservableCollection<DiskDrive> DriveList { get { return _driveList; } }
private DiskDrive _selectedDrive;
public DiskDrive SelectedDrive
{
    get { return _selectedDrive; }
    set { _selectedDrive = value; NotifyPropertyChanged(() => SelectedDrive); } }

我们也会在需要时通知它。

NotifyPropertyChanged(() => DriveList);
NotifyPropertyChanged(() => SelectedDrive);

class DiskDrive中,属性VolumeLabel的定义如下:

/// <summary>
/// Get the volume name of this disk. This is the friendly name ("Stick").
/// </summary>
/// <remarks>
/// When this class is used to identify a removed USB device, the Volume
/// property is set to String.Empty.
/// </remarks>
private string _volumeLabel;
public string VolumeLabel
{
    get { return _volumeLabel; }
    set { _volumeLabel = string.IsNullOrWhiteSpace(value) ? string.Format(LocalizationManager.Instance["XXXX"], SerialNumber) : value; }
} 

1 个答案:

答案 0 :(得分:0)

DiskDrive必须实施INotifyPropertyChangedVolumeLabel必须在更改后提升PropertyChanged事件。否则,绑定将不会更新。

另外,请注意,绑定到未实现INotifyPropertyChanged的类的属性时,很可能会泄漏内存。请参阅here