【发布时间】:2011-09-10 10:13:39
【问题描述】:
我有一个组合框,它有一个数据触发器,它根据 VM 中的 .NET 属性值设置其 SelectedIndex。我的问题是我无法让 setter 设置选定索引。
ItemSource 基于枚举数组。 Window 的 DataContext 是具有 Modulation 和 Bandwidth 属性的 VM。
我是 WPF 的新手,所以我确定我没有正确理解绑定,但我正在拉扯我的头发!提前感谢您的帮助。
风格如下。
<Style x:Key="BWCombBoxStyle" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
</Trigger>
<DataTrigger
Binding="{Binding Modulation}" Value="P25">
<Setter Property="SelectedIndex" Value="2"/>
</DataTrigger>
</Style.Triggers>
</Style>
这是组合框:
<ComboBox Name="bandwidth"
Height="Auto" Width="70"
Style="{StaticResource BWCombBoxStyle}"
ItemsSource="{Binding BandwidthOptions, Mode=OneWay, ValidatesOnDataErrors=true, NotifyOnValidationError=true, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding IFBandwidth, Mode=TwoWay, ValidatesOnDataErrors=True,
NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"/>
这是我的 VM 中的 .Net 属性:
public TMod Modulation
{
get { return modulation_; }
set { modulation_ = value; NotifyPropertyChanged("Modulation"); }
}
public Channel.TBnd IFBandwidth
{
get { return chan_.IFBandwidth; }
set
{
chan_.IFBandwidth = value;
NotifyPropertyChanged("IFBandwidth");
}
}
public Channel.TBnd[] BandwidthOptions
{
get
{
return (Channel.TBnd[])System.Enum.GetValues(typeof(Channel.TBnd));
}
}
这里是枚举:
public enum TMod
{
FM = 0,
AM = 1,
P25 = 2,
TRK = 3
}
public enum TBnd
{
Std = 0,
Nar = 1,
Wide = 2,
XWide = 3
}
【问题讨论】:
-
如果您不了解绑定,请阅读 this。
-
VisualStudio 的输出窗口是否出现绑定错误?
-
是不是像额外设置 SelecteValuePath 或使用 SelectedItem 绑定一样简单?需要触发器吗?您应该能够在视图模型中设置 IFBandwith ,它将在组合框中设置选定的值。
-
@Jerod:听起来更像是一个答案而不是评论。
标签: c# wpf xaml combobox datatrigger