我遇到了與我的組合框有關的問題。不知怎的,它可能會與自己不同步。例如,在我更換BlockSequenceFields後,只有下拉文本被修改。在下面,字段1已更新,但您可以看到它不反映在當前選定的項目中。WPF組合框不會更新當前選定的項目
我IsSynchronizedWithCurrentItem =真應該讓當前選定的項目像預期的那樣,但它似乎並沒有工作。我讀過很多目前的項目不匹配的stackoverflow帖子,但他們只是將IsSynchronizedWithCurrentItem設置爲true,它修復了他們的問題。
任何人都可以解釋爲什麼這不適合我嗎?
<ComboBox x:Name="SequenceFieldComboBox"
SelectedItem="{Binding BlockSequenceFieldIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding BlockSequenceFields, UpdateSourceTrigger=PropertyChanged}"
IsSynchronizedWithCurrentItem="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox
IsChecked="{Binding IsCalibrated, Mode=OneWay}"
IsEnabled="False">
</CheckBox>
<TextBlock
Text="{Binding}">
</TextBlock>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
編輯:張伯倫先生
// ViewModelBase implements INotifyPropertyChanged
public class BlockFieldViewModel : ViewModelBase
{
public BlockSequenceField SequenceField { get; set; }
public List<BlockSequenceCalibrationItemViewModel> Calibrations => this.SequenceField?.CalibrationList;
public bool IsCalibrated => this.Calibrations.TrueForAll(x => x.IsCalibrated == null || x.IsCalibrated == true);
public double AmplitudeThreshold => this.Calibrations.Max(x => x.Amplitude);
public int FieldNumber { get; set; }
public override string ToString()
{
string ret = string.Format(CultureInfo.CurrentCulture, "Field {0} ", this.FieldNumber);
if (Math.Abs(this.AmplitudeThreshold) > .00001)
{
ret = string.Concat(ret, string.Format(CultureInfo.CurrentCulture, "({0} mA)", this.AmplitudeThreshold));
}
return ret;
}
}
這裏是更大的視圖模型的更多細節,把它MainViewModel.cs。下面是在類相關領域
private ObservableCollection<BlockFieldViewModel> blockSequenceFields;
public ObservableCollection<BlockFieldViewModel> BlockSequenceFields
{
get => this.blockSequenceFields;
set
{
this.blockSequenceFields = value;
this.OnPropertyChanged("BlockSequenceFields");
}
}
private void RefreshFieldList()
{
// In order for the combo box text to update, we need to reload the items
var savedIndex = this.BlockSequenceFieldIndex; // to restore to current field.
var fieldList = this.CalibrationViewModel.FieldViewModels;
this.BlockSequenceFields = new ObservableCollection<BlockFieldViewModel>(fieldList);
this.BlockSequenceFieldIndex = savedIndex;
}
請向我們展示您的ViewModel,您的DataContext設置爲組合框。我正在尋找'公共ObservedableCollection中的'T'類代碼BlockSequenceFields {get; }' –
也許你忘了添加INotifyPropertyChanged接口到你的viewModel? – Demon
@ScottChamberlain我相當肯定datacontext是作爲組合框更新的一部分正確設置的。但是,我會明確地設置datacontext並查看它是否有效。我沒有用於設置datacontext的代碼,因此我將在xaml中執行此操作。 – user2619824