Skip to main content
 首页 » 编程设计

c#之来自 ItemsControl 项目的 RelayCommand 发送者

2024年02月24日43jirigala

我一直在使用 MVVM 的 RelayCommand 成功地将操作绑定(bind)到 XAML,但是我的 ItemsControl 有一个小问题。

    <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> 

在我的 View 模型中:

    public RelayCommand SelectDeviceCommand { get; set; } 
    private ObservableCollection<Device> Devices; 
 
    Devices = CreateListOfDevices(); 
 
    private void InitializeCommands() 
    { 
        SelectDeviceCommand = new RelayCommand((s) => MessageBox.Show(s.ToString())); 
    } 

如何在我的 View 模型中定义我的 SelectDeviceCommand 以便接收绑定(bind)到该项目的对象?

我的 SelectDeviceCommand 甚至没有被调用...(但我猜这是因为我需要让我的设备成为一个迷你 View 模型并在其中实现 SelectDeviceCommand,对吗?)

请您参考如下方法:

如果您像在 MVVM Light 应用程序中一样使用 ViewModelLocator,则可以使用 DataTemplate 中的 MainViewModel 引用

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

我发现这种方式比 ElementName 方式更清晰,但当然它假设 Main 属性在定位器中可用,并且 MainviewModel 被实例化为单例。显然,这并不总是可能的。在这种情况下,我认为 ElementName 解决方法是可以接受的。

在 WPF 中,您还可以将 RelativeSource 与 Mode=FindAncestor 一起使用,但我发现它更加困惑;)

关于“如何在我的 View 模型中定义我的 SelectDeviceCommand 以便接收绑定(bind)到该项目的对象?”这个问题,我不是 100% 确定我理解这个问题,但是如果您想获得由 DataTemplate 表示的项目(在本例中为设备),您应该使用 CommandParameter:

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

干杯, 洛朗