【发布时间】:2011-10-25 23:57:13
【问题描述】:
我有一个使用 ObservableCollection 作为源的 ComboBox。我的源绑定如下
<ComboBox IsEditable="False"
SelectedIndex="{Binding Source={x:Static Properties:CollectionControl.Settings}, Path=SamplingPeriodIndex, Mode=TwoWay}"
SelectionChanged="onPeriodControlSelectionChanged"
Name="PeriodControl"
ItemsSource="{StaticResource test}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding SamplingPeriod}" Visibility="{Binding Converter={StaticResource TrackVis}, ConverterParameter=GroupIndex}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
TrackVis 是一个转换器,它根据实现了 INotifyPropertyChanged 的外部属性确定元素是可见还是折叠。
第一次显示 ComboBox 时,一切都按预期工作,但 ComboBox 永远不会刷新以反映更改。我一定是遗漏了什么,但到目前为止我所尝试的一切都失败了。
这是转换器的代码
public class IsVisibleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var tempObj = (SamplingPeriods) value;
if (tempObj.GroupIndex >= CollectionControl.Settings.SamplingFrequencyIndex)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
还有,这里是合集
public class PeriodsCollection : ObservableCollection<SamplingPeriods>
{
public PeriodsCollection()
{
Add(new SamplingPeriods("1/16 of a second", 13));
Add(new SamplingPeriods("1/8 of a second", 12));
Add(new SamplingPeriods("1/4 of a second", 11));
Add(new SamplingPeriods("1/2 of a second", 10));
Add(new SamplingPeriods("1 second", 9));
Add(new SamplingPeriods("2 seconds", 8));
Add(new SamplingPeriods("4 seconds", 7));
Add(new SamplingPeriods("8 seconds", 6));
Add(new SamplingPeriods("16 seconds", 5));
Add(new SamplingPeriods("32 seconds", 4));
Add(new SamplingPeriods("64 seconds", 3));
Add(new SamplingPeriods("128 seconds", 2));
Add(new SamplingPeriods("256 seconds", 1));
Add(new SamplingPeriods("512 seconds", 0));
}
}
public class SamplingPeriods
{
public SamplingPeriods(string samplingPeriod, int groupIndex)
{
SamplingPeriod = samplingPeriod;
GroupIndex = groupIndex;
}
public string SamplingPeriod { get; private set; }
public int GroupIndex { get; private set; }
}
这个想法是选定的采样频率限制了可用的采样周期。采样频率索引范围从 0 到 11。例如,如果采样索引为 9,则唯一有效的采样周期将具有 GroupIndex >= 9. 其他采样周期将被折叠。
【问题讨论】:
-
为什么是静态资源而不是简单的属性名称?
-
对 TrackVis 或 selectedindex 或两者的更改?
-
在提出这样的问题时,具体说明未更新的内容非常重要。当您将新项目添加到集合中时,它们是否不会出现在
ComboBox中?当您更改代码中的绑定属性时,SelectedIndex是否不会更新?具体来说,发生了什么和没有发生什么?
标签: c# wpf xaml data-binding