【问题标题】:Issue with Binding for ComboBox in WPFWPF 中 ComboBox 的绑定问题
【发布时间】:2017-02-14 13:04:02
【问题描述】:

下面是代码

<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; }
} 

【问题讨论】:

  • 你能告诉我们SelectedDrive的定义吗?
  • 如何更改VolumeLabel
  • @AnjumSKhan ComboBox.SelectedItem 的默认值已经是 UpdateSourceTrigger=PropertyChanged。即使不是,该标志也会确定何时通知源,而 OP 的问题是通知目标。 OP:Mode=TwoWay 是默认设置。人们普遍倾向于花数小时设置Binding 的随机属性,而五分钟阅读 MSDN 会更有效率。
  • OP:您可能没有每次都为SelectedDrive 提高PropertyChanged。也有可能您将SelectedDrive 设置为一个不认为等于DriveList 中找到的任何对象的对象。 DriveList 中的项目是什么类型的?你从哪里得到SelectedDrive 的价值?
  • 请提供足够的代码让我们重现该问题。那么它几乎肯定会很容易解决。事实上,我们所能做的就是猜测,这是在浪费大家的时间。

标签: wpf mvvm prism


【解决方案1】:

DiskDrive 必须实现 INotifyPropertyChanged 并且 VolumeLabel 在更改时必须引发 PropertyChanged 事件。否则绑定不会更新。

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

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 2011-07-05
    • 2015-06-24
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多