2012-02-28 60 views
2

我目前正在使用MVVM的WPF應用程序。我有與建立一個風格的列表框,使其顯示像一個單選按鈕列表如下:在風格中綁定命令

<Style x:Key="RadioButtonList" TargetType="{x:Type ListBox}"> 
    <Setter Property="BorderBrush" Value="{x:Null}" /> 
    <Setter Property="BorderThickness" Value="0" /> 
    <Setter Property="ItemContainerStyle"> 
     <Setter.Value> 
      <Style TargetType="{x:Type ListBoxItem}" > 
       <Setter Property="Margin" Value="2" /> 
       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="{x:Type ListBoxItem}"> 
          <Border Background="Transparent"> 
           <RadioButton Focusable="False" IsHitTestVisible="False" IsChecked="{TemplateBinding IsSelected}" Content="{Binding Path=DisplayName}" Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}"> 
           </RadioButton> 
          </Border> 
         </ControlTemplate> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </Setter.Value> 
    </Setter> 
</Style> 

<ListBox Name="lbShipOtherMethodOptions" Style="{StaticResource RadioButtonList}" ItemsSource="{Binding Path=ShipOtherMethodOptions}" Margin="13,74,366,282" /> 

我試圖做的是綁定到一個單選按鈕命令,讓我可以關火了事件時進行選擇。我有我的視圖模型下面的代碼,但我似乎無法得到它的火:

private ICommand shipOtherMethodSelected; 
    public ICommand ShipOtherMethodSelected 
    { 
     get 
     { 
      return shipOtherMethodSelected ?? 
        (shipOtherMethodSelected = new RelayCommand(param => ShipOpenItems(), param => true)); 
     } 
    } 

    private void ShipOpenItems() 
    { 
     MessageBox.Show("GOT HERE"); 
    } 

我很新的WPF和MVVM,所以我可能失去了一些東西明顯。任何人都可以將我指向正確的方向嗎?

編輯: 根據jberger的建議,我放入了一些我試過的代碼,但沒有奏效。在該部分中設置斷點沒有被觸發,消息框也沒有顯示出來。

編輯2: 因此發件人檢查的DataContext後,原來有人指着我正在綁定單選按鈕的對象,而不是我的視圖模型。我更新了上面的代碼(將x:Name添加到我的窗口並更新了Command綁定),現在我得到的事件是在最初綁定時觸發的,但是當我選擇一個值時它不會觸發。好像我們現在變得非常接近了。

+0

你沒有在你的xaml – 2012-02-28 20:57:52

+0

中綁定'ShipOtherMethodSelected'抱歉,我試過了,但是我必須在複製/粘貼我的代碼之前恢復。我會解決這個問題 – 2012-02-28 21:07:15

+0

如果你刪除'Focusable =「False」IsHitTestVisible =「False」',會發生什麼?如果你鉤入'Click'事件,點擊時會觸發嗎? – 2012-02-28 21:15:53

回答

4

ShipOtherMethodSelected是你(主)ShippingVM不是你ShipItemVM,所以你需要設置

Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}" 

其中ShippingWindow是 「上面」 ListBoxItem

同樣元素的x:Name,該Focusable="False" IsHitTestVisible="False"拒絕點擊。移除setters。