2010-05-11 63 views
1

我一直在使用MVVM的RelayCommand成功地將操作綁定到XAML,但是我的ItemsControl有一個小問題。來自ItemsControl的RelayCommand發件人項目

<ItemsControl ItemsSource="{Binding Devices}" > 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Grid Width="100" Margin="4" > 
        <Button Command="{Binding Path=SelectDeviceCommand}" > 
         <Grid> 
          <Image Source="img_small.png"></Image> 
          <Image Source="{Binding Path=Logo}" /> 
         </Grid> 
        </Button> 
       </Grid> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

在我的視圖模型:

public RelayCommand SelectDeviceCommand { get; set; } 
    private ObservableCollection<Device> Devices; 

    Devices = CreateListOfDevices(); 

    private void InitializeCommands() 
    { 
     SelectDeviceCommand = new RelayCommand((s) => MessageBox.Show(s.ToString())); 
    } 

如何定義我的SelectDeviceCommand在我看來模式,以獲得綁定到該項目的對象?

我SelectDeviceCommand甚至不被稱爲...(但我猜是因爲我需要讓我的設備的迷你視圖模型,並在其中執行SelectDeviceCommand,是正確的?)

回答

4

如果使用ViewModelLocator像MVVM光應用程序,您可以從的DataTemplate內趕到MainViewModel參考與

<Button Command="{Binding Main.SelectDeviceCommand, Source={StaticResource Locator}}"> 

我覺得這種方式比的ElementName一個更清潔,但當然假定主屬性在定位器中可用,並且MainviewModel也被實例化爲單例。顯然這並不總是可能的。在這種情況下,我認爲ElementName解決方法是可以接受的。

在WPF中,你也可以使用與模式= FindAncestor一個的RelativeSource,但我覺得它甚至混亂;)

關於這個問題:「我如何定義我SelectDeviceCommand在我的視圖模型,以便接收對象綁定到該項目?「,我不能100%確定我理解這個問題,但是如果您想獲取由DataTemplate表示的項目(在本例中爲Device),則應該使用CommandParameter:

<Button Command="{Binding Main.SelectDeviceCommand, Source={StaticResource Locator}}" 
     CommandParameter="{Binding}"}"> 

乾杯, Laurent

0

呀,我已經擊中了這一個。我看到一些人用自定義的「CommandReference」類來解決這個問題,他們將這些類作爲資源添加到窗口中,但是我無法使其工作。因爲ViewModel是窗口的DataContext,所以我最後使用了元素綁定回窗口(或頁面)本身。首先,給你的窗口(或頁面)的名稱:

<Window ... 
    x:Name="me" /> 

然後綁定到窗口的datacontext直接,就像這樣:

<Button Command="{Binding DataContext.SelectDeviceCommand,ElementName=me}"> 

這爲我工作。這很混亂,但我認爲它很可讀。

0

我有一個用戶控件(X:NAME =「ControlClass」),它是一個模板裏面,它不上XAML 工作,我把它叫做這樣

<Button Content="New1" Command="{Binding DataContext.NewTabCommand,ElementName=ControlClass}"/> 



namespace Doit_Project.Modules.Tasks.ViewModels 
{ 
    [Export] 
    public class WindoTabViewModel : Doit_ProjectViewModelBase 
    { 
     public WindoTabViewModel() 
     { 

     } 

     private RelayCommand _newTabCommand; 
     public RelayCommand NewTabCommand 
     { 
      get { return _newTabCommand ?? (_newTabCommand = new RelayCommand(OnNewTab)); } 
     } 

     public void OnNewTab() 
     { 

     } 
    } 
}