2011-06-07 17 views
0

我有一個comboBox,它有一個數據觸發器,它根據VM中的.NET屬性值設置其SelectedIndex。我的問題是我無法讓setter設置Selected Index。無法使用DataTrigger在Combobox中設置SelectedValue

ItemSource基於枚舉數組。 窗口的DataContext是具有調製和帶寬屬性的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}"/> 

以下是.NET屬性在我的VM:

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 
    } 
+0

如果你不明白綁定讀** [this](http://msdn.microsoft.com/zh-cn/ -us /庫/ ms752347.aspx)**。 – 2011-06-07 21:10:30

+0

您是否在VisualStudio的輸出窗口中看到綁定錯誤? – 2011-06-07 21:26:24

+0

作爲另外設置SelecteValuePath或使用SelectedItem綁定來代替?需要觸發器嗎?你應該能夠在視圖模型中設置IFBandwith,並且它將在組合框中設置選定的值。 – 2011-06-07 21:39:51

回答

0

更改組合框綁定使用SelectedValue而不是Selecte dPath。當值更改時,將正確設置IFBandwidth視圖模型屬性。

觸發器到底會用什麼?這可能是一個更好的選擇,改變你的調製屬性是這樣的...

public TMod Modulation 
{ 
    get { return modulation_; } 
    set 
    { 
     modulation_ = value; 
     NotifyPropertyChanged("Modulation"); 

     if(modulation == TMod.P25) 
     { 
      IFBandwith = TBand.Wide; 
     } 
    } 
} 
+0

我真的改變了你的建議和工作的虛擬機。愚蠢的問題,但我看不到在ComboBox XAML中使用SelectedPath的位置。我想我不能理解綁定語法。 – Pat 2011-06-07 23:25:03

+0

對不起,我的意思是SelectedValuePath。雖然,第二個想法,我認爲它不會解決你的問題。 – 2011-06-08 00:22:05

+0

我想我希望能夠在XAML中做到這一切。你明白爲什麼它不起作用嗎?我想知道是否因爲類型不兼容而需要轉換器?有趣的是,我可以用一個設置IsEnabled屬性爲false的setter禁用組合框,所以我知道觸發器正在工作。 – Pat 2011-06-08 05:01:29

相關問題